I attempted to get the difference between two dates with:
date -d $(echo $(date -d \"Sun Dec 29 02:22:19 2013\" +%s) - $(date -d \"Sun Dec 28 03:22:19 2013\"
You can use:
date1="Sat Dec 28 03:22:19 2013"
date2="Sun Dec 29 02:22:19 2013"
date -d @$(( $(date -d "$date2" +%s) - $(date -d "$date1" +%s) )) -u +'%H:%M:%S'
And the output is:
23:00:00
However, for arbitrary differences over 24 hours, you have to start worrying about how the value for days will be represented. Negative values will also present problems.
The problem with this is that if you drop the format string, the date presented is:
Thu Jan 1 23:00:00 UTC 1970
So, while this works for the two given date/time values, it is not really a general solution.
Consider adding %j
for the day of year; it will work semi-sanely for up to 1 year's difference.
Otherwise, capture the difference in a variable and present the results with a separate calculation.
date1="Sat Dec 28 03:22:19 2013"
date2="Sun Dec 29 02:22:19 2013"
delta=$(( $(date -d "$date2" +%s) - $(date -d "$date1" +%s) ))
if [[ $delta -lt 0 ]]
then sign="-"; delta=${delta/^-/}
else sign="+"
fi
ss=$(( $delta % 60 ))
delta=$(( $delta / 60 ))
mm=$(( $delta % 60 ))
delta=$(( delta / 60 ))
hh=$(( $delta % 24 ))
dd=$(( $delta / 24 ))
printf "$sign%d %.2d:%.2d:%.2d\n" $dd $hh $mm $ss
Output:
+0 23:00:00
(Meaning: a positive difference of 0 days, 23 hours, 0 minutes, 0 seconds.) Splitting a number of days such as 1000 into years, months and days is fraught without any reference dates. Here, there are reference dates to help, but it would still be ... fun.