On macOS and Linux there a very useful command line tool "date". It is there out-of-the-box. You don't need to install anything in addition to access it.
If you run "date" command without parameters it will output date and time in the pretty common linux format:
$ date Tue Sep 24 13:49:09 MSK 2019
But it is possible to customize output. Here is some examples.
Output timestamp (number of seconds from 1st January 1970 in London):
$ date +%s 1569322149
By default "date" will output date and time info in the timezone that is set on computer (in the first example there was text "MSK" — it means timezone "Europe/Moscow". If you set environment variable TZ to the desired timezone then the output will be in that timezone:
$ TZ=America/Los_Angeles date Tue Sep 24 03:49:09 PDT 2019
You can use TZ environment variable to set UTC timezone as well, but UTC timezone is so frequently used so there is a special parameter -u to simplify usage:
$ date -u Tue Sep 24 10:49:09 UTC 2019
With -u parameter and format string you can output date time in ISO 8601 format:
$ date -u "+%Y-%m-%dT%H:%M:%SZ" 2019-09-24T10:49:09Z
You can use the date command to convert timestamp to human readable date time. To do it you need to specify timestamp as an option to -r parameter:
$ date -r 1257894000 Wed Nov 11 02:00:00 MSK 2009
Or, you can specify -u parameter to output date in the UTC timezone:
$ date -u -r 1257894000 Tue Nov 10 23:00:00 UTC 2009
(You can also combine parameters, the command "date -ur 1257894000" works exactly the same way)
Sometimes it is very useful to use date command in oneliners. You can redirect the output of some command to file with the name that is the current timestamp:
$ date > `date +%s`.txt
Or to create cron entry that run script every minute and save the output to the file with the current date in UTC timezone:
* * * * * /usr/bin/script --json >> /storage/`date -u +\%Y-\%m-\%d`.jsonl
But there is one pitfall in using date in cron. The percent sign in cron is a special sybmol. Instead of pure percent sign, you need to use backslash and the percent sign.
24 september 2019