-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtimedelta
executable file
·75 lines (69 loc) · 1.98 KB
/
timedelta
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env bash
###########################################################################
# Made by : Ewoud Dronkert
# Licence : GNU GPL v3
# Platform : macOS, Raspbian
# Requires : bash
# Location : ~/bin or /usr/local/bin
# Name : timedelta
# Version : 1.1.0
# Date : 2017-05-29
# Purpose : Calculate time value plus or minus "x" minutes
# Parameters : 1. <time> = 24h time as HMM or H:MM or H.MM (or HH etc.)
# : 2. +|-<delta> = time difference in minutes as +M or -M
# Output : New 24h time value as HMM
# Exit 0 : No errors
# 1 : Wrong parameter count
# 2 : Invalid time format
# 3 : Time hours >= 24
# 4 : Time minutes >= 60
# 5 : Delta not signed
# 6 : Delta not a number
###########################################################################
[ $# -ne "2" ] && echo "Usage: $(basename $0) <time> +|-<delta>" 1>&2 && exit 1
# First argument
TIME=${1//:}
TIME=${TIME//.}
L=${#TIME}
N=$(expr "$TIME" : '[0-9]*')
(( L < 3 || L > 4 || L != N )) && echo "First argument must be a time value, e.g. 1432 or 14:32." 1>&2 && exit 2
if (( L == 3 )); then
H=${TIME:0:1}
M=${TIME:1:2}
M=${M#0}
else
H=${TIME:0:2}
M=${TIME:2:2}
H=${H#0}
M=${M#0}
fi
(( H >= 24 )) && echo "Hours out of range (0-23)." 1>&2 && exit 3
(( M >= 60 )) && echo "Minutes out of range (0-59)." 1>&2 && exit 4
# Second argument
SIGN=${2:0:1}
[ "$SIGN" != "+" -a "$SIGN" != "-" ] && echo "Second argument must start with + or -." 1>&2 && exit 5
DELTA=${2:1}
N=$(expr "$DELTA" : '^0*')
DELTA=${DELTA:$N}
[ -z "$DELTA" ] && DELTA=0
L=${#DELTA}
N=$(expr "$DELTA" : '[0-9]*')
(( L != N )) && echo "Second argument must be a signed number." 1>&2 && exit 6
# Calculation
(( T = 60 * H + M ))
if [ "$SIGN" = "-" ]; then
(( T -= DELTA ))
while (( T < 0 )); do
(( T += 1440 ))
done
else
(( T += DELTA ))
while (( T >= 1440 )); do
(( T -= 1440 ))
done
fi
(( H = T / 60 ))
(( M = T - 60 * H ))
(( M < 10 )) && M="0$M"
echo "$H$M"
exit 0