How to get the difference between two dates

Using GNU date, first parse the dates into timestamps and work on those:

# get the seconds passed since 2010 (localtime)
echo $(($(date +%s) - $(date -d "2010-01-01 00:00:00" +%s)))

To print that 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=$(($(date +%s) - $(date -d "2010-01-01 00:00:00" +%s)))
# 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."

To parse the timestamp back to a readable date, using GNU date:

# get a date that is 90 days into the future (recent GNU date)
date -d "@$(($(date +%s) + 60 * 60 * 24 * 90))"

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


CategoryShell