How to get the difference between two dates

It's best if you work with timestamps throughout your code, and then only convert timestamps to human-readable formats for output. If you must handle human-readable dates as input, then you will need something that can parse them.

Using GNU date, for example:

# get the seconds passed since Jan 1, 2010 (local-time)
then=$(date -d "2014-10-25 00:00:00" +%s)
now=$(date +%s)
echo $(($now - $then))

# To avoid "Daylight Saving Time" aka "Daylight Savings Time", "DST" or "Summer Time" 
# and/or Local time adjustments,
# is better to use UTC time:
then=$(date -u -d "2014-10-25 00:00:00" +%s)
now=$(date -u +%s)
echo $(($now - $then))

To print a duration as a human-readable value (within 365 days - 1 year) use date capacity to add and subtract time :

date -u -d "2014-01-01 $now sec - $then sec" +"%j days %T"

Or, a little more explicit:

date -u -d "2014-01-01 $now sec - $then sec" +"%j days %H hours %M minutes and %S seconds"

To print a duration that is longer than a year, you'll have to do some external additional math.

The concept could be extended to nanoseconds, as this:

then=$(date -u -d "2014-10-25 00:00:00" +"%s.%N")
now=$(date -u +"%s.%N")
date -u -d "2014-01-01 $now sec - $then sec" +"%j days %T.%N"

# will print:      046 days 21:03:50.296901858

To convert the timestamp back to a human-readable date, using recent GNU date:

date -d "@$now"

(See FAQ #70 for more about converting Unix timestamps into human-readable dates.)

BashFAQ/102 (last edited 2014-12-19 21:07:32 by BinaryZebra)