Convert between date formats from the command line

By on

The date utility returns the current date and time. The desired output format is passed in through a trailing argument that starts with a plus sign. It needs to be wrapped in quotes if it contains any whitespace.

date
Thu Oct 17 09:41:10 CEST 2017
date +%Y-%m-%d
2017-10-17
date +"%B %d, %Y"
October 17, 2017

On macOS (or other derivatives of BSD) passing a date to the date utility overwrites the system date unless the -j flag is passed. With that flag, the utility allows passing a test date to be reformatted. The test date needs to be formatted as [[[mm]dd]HH]MM[[cc]yy][.ss] by default or we can pass a custom input format with -f.

date -j 110200361991.35
Sat Nov  2 00:36:35 CET 1991
date -f %Y-%m-%d -j 1991-11-02
Sat Nov  2 12:33:57 CET 1991

GNU date uses the --date argument to pass in dates, and it figures out the input format on its own.

date --date=1991-11-02
Sat Nov  2 00:00:00 UTC 1991

By setting the input and output format, we can use the date utility to reformat dates.

date -jf %Y-%m-%d 1991-11-02 +"%B %d, %Y" # BSD
November 02, 1991
date --date=1991-11-02 +"%B %d, %Y" # GNU
November 02, 1991