Quickly calculate date differences

The "n weeks after a date" is easy with GNU date(1):

$ date -d 'now + 3 weeks'
Tue Dec  6 23:58:04 EST 2011
$ date -d 'Aug 4 + 3 weeks'
Thu Aug 25 00:00:00 EST 2011
$ date -d 'Jan 1 1982 + 11 weeks'
Fri Mar 19 00:00:00 EST 1982

I don't know of a simple way to calculate the difference between two dates, but you can wrap a little logic around date(1) with a shell function.

datediff() {
    d1=$(date -d "$1" +%s)
    d2=$(date -d "$2" +%s)
    echo $(( (d1 - d2) / 86400 )) days
}
$ datediff '1 Nov' '1 Aug'
91 days

Swap d1 and d2 if you want the date calculation the other way, or get a bit fancier to make it not matter. Furthermore, in case there is a non-DST to DST transition in the interval, one of the days will be only 23 hours long; you can compensate by adding ½ day to the sum.

echo $(( (((d1-d2) > 0 ? (d1-d2) : (d2-d1)) + 43200) / 86400 )) days

For a set of portable tools try my very own dateutils. Your two examples would boil down to one-liners:

ddiff 2011-11-15 2012-04-11
=>
  148

or in weeks and days:

ddiff 2011-11-15 2012-04-11 -f '%w %d'
=>
  21 1

and

dadd 2011-11-15 21w
=>
  2012-04-10

Important note regarding Ubuntu installation:

These very same dateutils are available as a Ubuntu package, and hence installable through sudo apt install dateutils.

However, commands need to be preceded by a dateutils. prefix, as in dateutils.ddiff 2019-03-28 2019-05-16

They are also available in Fedora and in Fedora EPEL for RHEL or CentOS with sudo dnf install dateutils. In Fedora, these packages do not require a prefix but use the long names — e.g, datediff and dateadd instead of ddiff and dadd.


A python example for calculating the number of days I've walked the planet:

$ python
>>> from datetime import date as D
>>> print (D.today() - D(1980, 6, 14)).days
11476

Tags:

Date