banner

For a list of BASHing data 2 blog posts see the index page.    RSS


The difference between two dates: easy solutions and hard

On the BASH command line, getting the duration between two dates is straightforward (sort of) using the date command.

"Duration" here means either "number of days not including the start date" or "number of days not including the end date".

One commonly recommended method is to express each of the two dates in seconds of the UNIX epoch, then calculate (with integer arithmetic) the difference in seconds and divide by the number of seconds in a day, namely 86400. A command for this is:

echo $((($(date -d "YYYY-MM-DD" +%s) - $(date -d "YYYY-MM-DD" +%s))/86400))

For example:

long way

I wrote "sort of" because that's a fairly complicated construction. With less typing, you can use datediff from Sebastian Freundt's "dateutils" package, which is available in the repositories. Note that to get a positive result with datediff you need to put the later date last:

dateutils.ddiff [earlier date] [later date]

dateutils way

The dateutils.ddiff construction is required in Debian. Other OSes have other ways to invoke the same command.

Another command-line date utility in the repos is Arun Prakash Jana's pdd utility. It needs year, month and day to be separate arguments after the -d (difference) option, but pdd understands month strings:

pdd -d [later date] [earlier date]

pdd way

Out of habit I look for easy ways to do repetitive jobs. In this case I wrote a function, "durn", based on the date command above. I've added the -u option so that the UNIX epoch seconds are for Universal Time; this avoids possible time zone and daylight savings issues:

durn() { echo $((($(date -u -d "$1" +%s)-$(date -u -d "$2" +%s))/86400)); }

durn way

Next post:
2025-10-31   A data table full of ghosts


Last update: 2025-10-24
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License