Posts tonen met het label date time bash calculate. Alle posts tonen
Posts tonen met het label date time bash calculate. Alle posts tonen

donderdag 23 januari 2014

Calculate Time in bash

#!/bin/sh
# +0:00 or +00:00 or -0:00 or -00:00
# returns seconds as int
function getSeconds() {
 SIGN=$(echo $1|cut -c1)"1"
 HOUR=$(echo $1|cut -d':' -f1|cut -c2- )
 HOUR=$(echo "${HOUR#0}")
 MIN=$(echo $1|cut -d':' -f2)
 MIN=$(echo "${MIN#0}")
 SECONDS=$(((HOUR * 3600) + (MIN * 60)))
 echo $((SECONDS * SIGN))
}

# seconds as int -10, 0 or 70
# returns +0:00 or +23:00 or -1:00 or -11:00
function formatSecondsToTime() {
 dt=$1
 SIGN="+"
 if [[ $1 -lt 0 ]] ; then
  SIGN=$(echo $1|cut -c1)
  dt=$(echo $1|cut -c2-)
 fi
 dm=$(((dt / 60  ) % 60))
 dh=$(((dt / 3600) % 24))
 VALUE=$(printf '%d:%02d' $dh $dm)
 echo $SIGN$VALUE
}

function addMinutes(){
 SEC1=$(getSeconds $1)
 SEC2=$(getSeconds $2)
 CALC=$((SEC1 + SEC2 ))
 #echo "$1 $2 $SEC1 + $SEC2 = $CALC formatted= $(formatSecondsToTime $CALC)"
 echo $(formatSecondsToTime $CALC)
}
function printTime() {
 SECONDS=$(getSeconds $1)
 echo "$1 $SECONDS $(formatSecondsToTime $SECONDS)"
 #echo "$1 $SECONDS $(formatSecondsToTime $SECONDS) $(getSign $1) $(getHours $1) $(getMinutes $1)"
}

# test
printTime "+00:01"
printTime "-00:10"
printTime "+01:00"
printTime "+09:10"
printTime "+09:01"
printTime "-11:10"
printTime "-09:59"
printTime "-23:59"
printTime "-10:59"
printTime "-000:059"
printTime "-25:89"
printTime "-24:61"
printTime "-24:00"
Output:
+00:01 60 +0:01
-00:10 -600 -0:10
+01:00 3600 +1:00
+09:10 33000 +9:10
+09:01 32460 +9:01
-11:10 -40200 -11:10
-09:59 -35940 -9:59
-23:59 -86340 -23:59
-10:59 -39540 -10:59
-000:059 -3540 -0:59
-25:89 -95340 -2:29
-24:61 -90060 -1:01
-24:00 -86400 -0:00
time="+01:22"
echo $(addMinutes $time "+0:01")
echo $(addMinutes $time "-0:01")
echo $(addMinutes $time "+1:01")
echo $(addMinutes $time "-1:01")
echo $(addMinutes $time "+24:01")
echo $(addMinutes $time "-24:01")
Output:
+1:23
+1:21
+2:23
+0:21
+1:23
-22:39