I rarely ever use the date command, but when I need it I almost always struggle to get the right incantation. So, I'm just going to record such examples in this blog post (and some good to know features).

There'll also be learning resources linked at the end of the post.


Really basic examples

The date command by itself shows the current time. But that's rarely what I need, since I could just use the calendar widget at the bottom of my desktop screen. Perhaps useful to copy the string format and modify system time with the -s option?

# use the -u option for UTC (Coordinated Universal Time)
$ date
Wednesday 31 July 2024 03:53:01 PM IST

Instead, I need particular parts in a particular format. For example, to represent the time component in a dynamically constructed filename as part of a shell script.

# same as: date +%F or date -I
$ date +%Y-%m-%d
2024-07-31

$ date +%Y/%m/%d
2024/07/31
$ date +%y-%m-%d
24-07-31

# use 'b' and 'B' for month names
$ date +%a
Wed
$ date +%A
Wednesday

You can use %x to get the locale representation:

$ date +%x
31/07/24

For hours, minutes and seconds:

# same as: date +%T
$ date +%H:%M:%S
16:00:32

# same as: date +%Y-%m-%dT%H:%M:%S%:z
$ date -Iseconds
2024-07-31T16:09:27+05:30

Displaying and converting epoch seconds

# total seconds since the epoch (1970-01-01 00:00:00 UTC)
$ date +%s
1722422393

$ date -d @1722422393 +'%F %T'
2024-07-31 16:09:53

You can also provide an input file for conversion using the -f option:

$ cat epochs.txt
@0000000000
@1234567890
@2222222222

# recall that the -u option gives you UTC
$ date -u -f epochs.txt +'%F %T'
1970-01-01 00:00:00
2009-02-13 23:31:30
2040-06-02 03:57:02

Date arithmetic

$ date -I
2024-08-02
$ date -d '+1 month 4 days'
Friday 06 September 2024 01:24:44 PM IST

# same as: date -d '-20 days' +%F
# you can also use '20 days ago'
$ date -I -d '-20 days'
2024-07-13

For my learnbyexample weekly newsletter, I use a script to generate a template issue. I use the arithmetic feature as shown below:

# prev_date variable gets the value from the previous newsletter issue
$ prev_date='2024-02-23'
$ date -d "$prev_date"' +7 days' +%F
2024-03-01