ISO 8601 and Date Arithmetic on the Command-Line
Why?
- typing full correct dates is painful
- date arithmetic is useful – especially in bash scripts
ISO 8601 Format
When you use date
, you might not realize its full potential:
it’s better if you provide a format:
Check man date
for all the formats you need. But why wouldn’t you use
ISO 8601?
Specify an Absolute Date
You can specify a date to format with -d
, it recognizes a bunch of formats:
Specify a Relative Date
The -d
flag also accepts relative dates:
The documentation says:
- “last” means -1
- “this” means 0
- “next” means 1
- “ago”, as a suffix, means negative
- “now” and “today” mean 0
There is support for units (in singular and plural):
- year
- month
- week
- day
- hour
- min(ute)
- sec(ond)
Date Arithmetic!
Yes, you can combine both absolute and relative dates:
Some of these are useful, others not so much… it depends what you need.
Think about your edge cases carefully:
This page (bottom) discusses this gotcha and possible workarounds.
The subpages of Date input formats contain all the details from above and more… For example, I didn’t even try to discuss times, timezones and all their terrifying complexity.
My iso8601
Helper
Because I use ISO 8601 dates in a bunch of command-line contexts, I wrote a helper.
Dump the script (call it iso8601
) in your PATH:
The $*
sequence means you don’t need to (but still can) quote your inputs:
I use this script mainly from inside Vim. I type !!iso8601 <bla bla>
on a blank line to insert a date.