The date command is crufty.
It can be used for both setting and displaying the current date.
Setting the date requires root privilege and is obsolete since modern systems have a daemon. On Linux the daemon is ntpd, though I think systemd has taken over the responsibility. On Mac the daemon is timed.
The date flags are not standardized for the most part. POSIX only specifies two flags: -u and +CONVERSION_SPECIFICATIONS. As you can see from the table below, flags available on Linux are not necessarily available on Mac and vice versa.
The %s conversion specification for the UNIX epoch is not required by POSIX but is supported on both Linux and Mac.
Linux | Mac | |
---|---|---|
set current date | $ date MMDDhhmm[[CC]YY] | $ date [[[mm]dd]HH]MM[[cc]yy] |
set current date using 8601 timestamp | $ date -s 2018-10-01T00:00:00 | $ date -f %Y-%m-%dT%H:%M:%S 2018-10-01T00:00:00 |
set current date using UNIX epoch | $ date -s @1543336412 | $ date -f %s 1543336412 |
set current date using input format | $ date -f %Y%m%d%H%M%S 20181001000000 | |
display current date | $ date Tue Nov 27 08:19:29 PST 2018 |
$ date Tue Nov 27 08:19:29 PST 2018 |
display current UTC date | $ date -u Tue Nov 27 16:27:30 UTC 2018 |
$ date -u Tue Nov 27 16:27:30 UTC 2018 |
display current date according to locale | $ LC_ALL=fr_FR date Mar 27 nov 2018 08:19:24 PST $ LC_TIME=fr_FR date Mar 27 nov 2018 08:38:11 PST |
|
display current date using output format | $ date +%Y-%m-%dT%H:%M:%S 2018-11-27T08:29:46 |
$ date +%Y-%m-%dT%H:%M:%S 2018-11-27T08:29:46 |
display current date as UNIX epoch | $ date +%s 1543336412 |
$ date +%s 1543336412 |
parse date using input format and display | $ date -j -f %Y%m%d%H%M%S 20181001000000 Mon Oct 1 00:00:00 PDT 2018 |
|
parse ISO 8601 timestamp and display | $ date -d 2018-10-01T00:00:00 Mon Oct 1 00:00:00 PDT 2018 |
$ date -j -f %Y-%m-%dT%H:%M:%S 2018-10-01T00:00:00 Mon Oct 1 00:00:00 PDT 2018 |
parse UNIX epoch and display | $ date -d @1543336412 Tue Nov 27 08:33:32 PST 2018 |
$ date -j -f %s 1543336412 Tue Nov 27 08:33:32 PST 2018 |
parse date using input format and display using output format | $ date -j -f %Y%m%d%H%M%S 20181001000000 +%Y-%m-%dT%H:%M:%S 2018-10-01T00:00:00 |
|
display one hour before current date | $ date -d '-1 hour' | $ date -j -f %s $(($(date +%s) - 3600)) |