Automating Date Ranges

Problem

You have one date (perhaps from Supplying a Default Date) and you would like to generate the other automatically.

Solution

The GNU date command is very powerful and flexible, but the power of -d isn’t documented well. Your system may document this under getdate (try the getdate manpage). Here are some examples:

$ date '+%Y-%m-%d %H:%M:%S %z' 2005-11-05 01:03:00 -0500 $ date -d 'today' '+%Y-%m-%d %H:%M:%S %z' 2005-11-05 01:04:39 -0500 $ date -d 'yesterday' '+%Y-%m-%d %H:%M:%S %z' 2005-11-04 01:04:48 -0500 $ date -d 'tomorrow' '+%Y-%m-%d %H:%M:%S %z' 2005-11-06 01:04:55 -0500 $ date -d 'Monday' '+%Y-%m-%d %H:%M:%S %z' 2005-11-07 00:00:00 -0500 $ date -d 'this Monday' '+%Y-%m-%d %H:%M:%S %z' 2005-11-07 00:00:00 -0500 $ date -d 'last Monday' '+%Y-%m-%d %H:%M:%S %z' 2005-10-31 00:00:00 -0500 $ date -d 'next Monday' '+%Y-%m-%d %H:%M:%S %z' 2005-11-07 00:00:00 -0500 $ date -d 'last week' '+%Y-%m-%d %H:%M:%S %z' 2005-10-29 01:05:24 -0400 $ date -d 'next week' '+%Y-%m-%d %H:%M:%S %z' 2005-11-12 01:05:29 -0500 $ date -d '2 weeks' '+%Y-%m-%d %H:%M:%S %z' 2005-11-19 01:05:42 -0500 $ date -d '-2 weeks' '+%Y-%m-%d %H:%M:%S %z' 2005-10-22 01:05:47 -0400 $ date -d '2 weeks ago' '+%Y-%m-%d %H:%M:%S %z' 2005-10-22 01:06:00 -0400 $ date -d '+4 days' '+%Y-%m-%d %H:%M:%S %z' 2005-11-09 01:06:23 -0500 $ date -d '-6 days' '+%Y-%m-%d %H:%M:%S %z' 2005-10-30 01:06:30 -0400 $ date -d '2000-01-01 +12 days' '+%Y-%m-%d %H:%M:%S %z' 2000-01-13 00:00:00 -0500 $ date -d '3 months 1 day' ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.