Create a date in the future for use in Bash scripts on BSD/Mac OSX

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, May 14, 2020

Follow me on Twitter as @mattiasgeniar

Annoyingly, the date command differs vastly between Linux & BSD systems. Mac, being based on BSD, inherits the BSD version of that date command.

It took me longer to admit to figure out how to set a date in the future using the date command on a Mac. It requires this arcane syntax.

EXPIRATIONDATE=$(date -j -f "%a %b %d %T %Z %Y" "`date -v+12H`" "+%Y-%m-%dT%H:%M:00")

The above takes “now + 12 hours” as the new date, and formats it as "+%Y-%m-%dT%H:%M:00" - the last parameter.

The -f flag indicates how to parse the date format supplied by the middle parameter.

To get a date in the future, you use the -v command and supply the desired date shift:

date -v+12H

This generates a new date 12 hours into the future. To supply multiple shifts, repeat the -v parameter.

date -v+12H -v-1d -v+10M

Which does: + 12 hours, -1 day, + 10 minutes.

The long command at the top outputs this:

2020-05-15T08:37:00

I hope I won’t have to Google this again!



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.