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 (localtime)
then=$(date -d "2010-01-01 00:00:00" +%s)
now=$(date +%s)
echo $(($now - $then))

To print a duration as a human-readable value you'll have to do some math:

# some constants
minute_secs=60 hour_secs=$((60 * minute_secs)) day_secs=$((24 * hour_secs))
# get total
seconds_since=$(($now - $then))
# parse
days=$((seconds_since / day_secs))
hours=$((seconds_since % day_secs / hour_secs))
minutes=$((seconds_since % day_secs % hour_secs / minute_secs))
seconds=$((seconds_since % day_secs % hour_secs % minute_secs))
# pretty-print
echo "$days days, $hours hours, $minutes minutes and $seconds seconds."

Or, without the verbose labels:

# Bash/ksh
((duration = now - then))
((days = duration / 86400))
((duration %= 86400))
((hours = duration / 3600))
((duration %= 3600))
((minutes = duration / 60))
((seconds = duration % 60))
echo "$days days, $hours hours, $minutes minutes and $seconds seconds."

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 2010-07-30 13:46:05 by GreyCat)