Date Calculation – Quickly Calculate Date Differences

date

I often want to make some quick date calculations, such as:

  • What is the difference between these two dates?
  • What is the date n weeks after this other date?

I usually open a calendar and count the days, but I think there should be a program/script that I can use to do these kinds of calculations. Any suggestions?

Best Answer

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'  # Note: answer should be 92 days but in my timezone, DST starts between the dates.
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
Related Question