Shell script to get difference between two dates Shell script to get difference between two dates shell shell

Shell script to get difference between two dates


Using only date and shell arithmetics:

echo $((($(date -d "2010-06-01" "+%s") - $(date -d "2010-05-15" "+%s")) / 86400))


There's a solution that almost works: use the %s date format of GNU date, which prints the number of seconds since 1970-01-01 00:00. These can be subtracted to find the time difference between two dates.

echo $(( ($(date -d 2010-06-01 +%s) - $(date -d 2010-05-15 +%s)) / 86400))

But the following displays 0 in some locations:

echo $((($(date -d 2010-03-29 +%s) - $(date -d 2010-03-28 +%s)) / 86400))

Because of daylight savings time, there are only 23 hours between those times. You need to add at least one hour (and at most 23) to be safe.

echo $((($(date -d 2010-03-29 +%s) - $(date -d 2010-03-28 +%s) + 43200) / 86400))

Or you can tell date to work in a timezone without DST.

echo $((($(date -u -d 2010-03-29 +%s) - $(date -u -d 2010-03-28 +%s)) / 86400))

(POSIX says to call the reference timezone is UTC, but it also says not to count leap seconds, so the number of seconds in a day is always exactly 86400 in a GMT+xx timezone.)


OSX date is different than GNU date. Got it working like this in OSX. This is not portable solution.

start_date=$(date -j -f "%Y-%m-%d" "2010-05-15" "+%s")end_date=$(date -j -f "%Y-%m-%d" "2010-06-01" "+%s")echo $(( ($end_date - $start_date) / (60 * 60 * 24) ))

Idea is still same as in the other answers. Convert dates to epoch time, subtract and convert result to days.