bash-formatting-dates

2020-08-19

 | 

~2 min read

 | 

324 words

I was working on updating a small shell script I have to create a new note and I wanted to include the date. That led me to discover the date command.

Dates are a endlessly fascinating / complicated problem. I’ve written about dates numerous times before, like my efforts to convert to utc with Python or how date math with vanilla Javascript (which I then followed up with one about DayJS). Using dates in Bash scripts was simply a new domain to an old problem. As is often the case, however, I ended up learning a few things.

Formatting Dates With Bash

NixCraft has a great post on how to format dates and all of the options. Many other examples can be found by looking at the manual which can be found in the terminal:

man date
DATE(1)                   BSD General Commands Manual                  DATE(1)

NAME
     date -- display or set date and time

SYNOPSIS
     date [-jRu] [-r seconds | filename] [-v [+|-]val[ymwdHMS]] ... [+output_fmt]
     date [-jnu] [[[mm]dd]HH]MM[[cc]yy][.ss]
     date [-jnRu] -f input_fmt new_date [+output_fmt]
     date [-d dst] [-t minutes_west]
DESCRIPTION
...

For formatting, it’s the [+output_fmt] option that’s relevant.

For example, to get today’s date in UTC time, you might do the following:

$ date -u +%Y-%m-%d:%T%z
# or
$ date -u +"%Y-%m-%d:%T%z"

On August 3rd, this would print:

2020-08-03:16:05:16+0000

The benefit of using the " is that it allows for spaces, e.g.,

date -u +"%Y-%m-%d %T%z"

With the space, the date is separated from the time:

2020-08-03 16:05:16+0000

While it’s not my favorite format, I do like the -R option too as it is compliant with RFC 2822 making it a versatile format for future conversions. By default, -R is in local time, but it can be converted by also using the -u option:

date +R
date +Ru
Mon, 03 Aug 2020 11:05:16-0500
Mon, 03 Aug 2020 16:05:16+0000


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!