6

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?.

3 Answers3

11

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.

heemayl
  • 56,300
6

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)"
  • This works only if the diff is less than 24 hours. – rudimeier Oct 18 '16 at 09:42
  • Updated answer to address your thoughts. The original question was asking for hours and minutes. This could be interpreted in several ways, including just looking for the hours/minutes difference (hands of the clock difference). While I agree that the most common case is a person looking for total time difference, I really don't know for sure what the poster wanted more precisely. Nevertheless, good feedback. – Steve Amerige Oct 18 '16 at 10:20
4
$ 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
rudimeier
  • 10,315