0

I'm trying to set the difference (in hours, minutes and seconds) between two dates into a variable. The format is +%y%m%d%H%M%S (for example: 170607162412).

For example: 170607162400 and 170607162410 = 00:00:10

I tried a lot but i couldn't figure it out.

NetMonk
  • 55
  • 6
  • Did you try the date command? – 123 Jun 07 '17 at 14:34
  • Yes, I tried to use the advice from this page: https://stackoverflow.com/questions/20831765/find-difference-between-two-dates-in-bash (sorry for not mentioning that) – NetMonk Jun 07 '17 at 14:36

2 Answers2

1

Take a look here: http://www.unix.com/tips-and-tutorials/31944-simple-date-time-calulation-bash.html. The trick is to convert your date to a timestamp (seconds since Jan 01 1970. UTC). Than you can add and remove seconds and even substract dates from each other.

date2stamp () {
    date --utc --date "$1" +%s
}

stamp2date (){
    date --utc --date "1970-01-01 $1 sec" "+%Y-%m-%d %T"
}

dateDiff (){
    case $1 in
        -s)   sec=1;      shift;;
        -m)   sec=60;     shift;;
        -h)   sec=3600;   shift;;
        -d)   sec=86400;  shift;;
        *)    sec=86400;;
    esac
    dte1=$(date2stamp $1)
    dte2=$(date2stamp $2)
    diffSec=$((dte2-dte1))
    if ((diffSec < 0)); then abs=-1; else abs=1; fi
    echo $((diffSec/sec*abs))
}
realbart
  • 3,497
  • 1
  • 25
  • 37
0

Use date to put into seconds, then subtract. Then parse out minutes and seconds:

$ var1=170607162400
$ var2=170607162410
$ var="$var1"
$ date1="20${var:0:2}/${var:2:2}/${var:4:2 {var:6:2}:${var:8:2}:${var:10:2}"
$ var="$var2"
$ date2="20${var:0:2}/${var:2:2}/${var:4:2} ${var:6:2}:${var:8:2}:${var:10:2}"
$ sec1=$( date -d "$date1" '+%s' )
$ echo $sec1
1496867040
$ sec2=$( date -d "$date2" '+%s' )
$ echo $sec2
1496867050
$ dt=$(( sec2 - sec1 ))
$ echo $dt
10
$ min=$(( dt/60 ))
$ sec=$(( dt - 60*min ))
$ minsec=$( printf "%02d:%02d" "$min" "$sec" )
$ echo "$minsec"
00:10

If you need hours, too, change those last lines like so:

$ hrs=$(( dt/3600 ))
$ min=$(( (dt - 3600*hrs) / 60 ))
$ sec=$(( dt - 3600*hrs - 60*min ))
$ hms=$( printf "%d:%02d:%02d" "$hrs" "$min" "$sec" )
Jack
  • 5,801
  • 1
  • 15
  • 20