How to Print an ISO-Formatted Date in the Terminal
There are many code snippets online about how to ISO-format a date using the date command in a Linux (or similar) terminal, but some of them are verbose. There’s actually an easy shortcut that isn’t always mentioned.
Here is a quote from the man page for the date utility:
-I[FMT]— Use ISO 8601 output format. FMT may be omitted, in which case the default is ‘date’. Valid FMT values are ‘date’, ‘hours’, ‘minutes’, and ‘seconds’. The date and time is formatted to the specified precision. When FMT is ‘hours’ (or the more precise ‘minutes’ or ‘seconds’), the ISO 8601 format includes the timezone.
Examples of the date Command
If you just need the year, month and day, use -I by itself:
date -I
That will output:
2022-11-05
Including Hours
If you want to include hours, use this form:
date -Ihours
That will output:
2022-11-05T11-07:00
Including Minutes
For minutes:
date -Iminutes
which produces this:
2022-11-05T11:49-07:00
Including Seconds
And finally, with seconds:
date -Iseconds
which produces this:
2022-11-05T11:50:42-07:00
It’s a simple shortcut that can save a bit of time.
For more details, type man date in the terminal.