Celeb Glow
updates | March 18, 2026

Difference between dates in hour in bash

How can I find the difference between two dates which are in the format

date +"%H-%M-%d-%m-%Y"

And also I want the difference in hours. How can I find this using a single command.

4

1 Answer

If the dates are in a file a one-per-line, like, say:

16-49-24-02-2016
16-49-25-02-2016

Then you could use awk:

awk -F- 'NR==1 { then = mktime(sprintf("%s %s %s %s %s 00", $5, $4, $3, $1, $2))
}
NR==2 { now = mktime(sprintf("%s %s %s %s %s 00", $5, $4, $3, $1, $2)); printf "%s\n", (now - then)/3600
}' input.txt

The mktime function expects time in YYYY MM DD HH MM SS, so we split the given timestamp and convert it to that format (using 00 for seconds). The difference between the timestamps is in seconds, so we divide by 3600 to get the hours.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy