I am looking to calculate time difference between the two below
Value1=2016-10-13 14:19:23
Value2=2016-10-13 18:19:23
I want to get difference in the form of hours/minutes. Any quick solution available?.
I am looking to calculate time difference between the two below
Value1=2016-10-13 14:19:23
Value2=2016-10-13 18:19:23
I want to get difference in the form of hours/minutes. Any quick solution available?.
You can use date
(assuming the GNU implementation) with command substitution, and to get the difference between the times use arithmetic expansion:
% Value1='2016-10-13 14:19:23'
% Value2='2016-10-13 18:19:23'
% echo "$(($(date -d "$Value2" '+%s') - $(date -d "$Value1" '+%s')))"
14400
The result is in seconds.
The answer in hours/minutes/seconds:
date -u -d @$(($(date -d "$Value2" '+%s') - $(date -d "$Value1" '+%s'))) '+%T'
The answer in just hours/minutes (as originally requested):
date -u -d @$(($(date -d "$Value2" '+%s') - $(date -d "$Value1" '+%s'))) '+%H:%M'
The above supposes that the user is interested in only the difference in hour and minutes and ignores day differences. The answer all depends on what is wanted.
To deal with differences greater than or equal to a day:
Value1='2016-10-13 14:19:23'
Value2='2016-10-18 10:34:58'
D1=$(date -d "$Value1" '+%s'); D2=$(date -d "$Value2" '+%s')
echo "$(((D2-D1)/86400)):$(date -u -d@$((D2-D1)) +%H:%M)"
yields:
4:20:15
And for various shells, one can also do things such as in Bash:
declare -i Delta=D2-D1
declare -i Days=Delta/86400
echo "$Days:$(date -u -d@$Delta +%H:%M)"
$ datediff -f "%H hours and %M minutes" "2016-10-13 14:19:23" "2016-10-13 18:19:23"
4 hours and 0 minutes
datediff is from the dateutuils package. http://www.fresse.org/dateutils/
Note in opposite to the date
command, dateutils ignores locale settings by default using GMT. This can make one hour difference regarding the adjustment to daylight savings time.
Compare:
$ datediff -f "%H:%M" "2016-10-29 14:00:00" "2016-10-30 14:00:00"
24:0
and
$ datediff --from-zone=Europe/Berlin -f "%H:%M" "2016-10-29 14:00:00" "2016-10-30 14:00:00"
25:0