Date
The date
unix utility can set or show the current time.
Date output cheat sheet
The date utility outputs the date and time using the ISO 8601 format by default (which looks something like Fri Jul 2 22:27:43 MDT 2021
). This can be overridden by passing in a custom format string that always begins with a +
symbol. Below are some examples of some commonly used formats:
Format | Output | Comment |
---|---|---|
date
|
Thu Jun 11 14:00:47 MDT 2020 | Default ISO8601 output |
date +%T
|
12:34:56 | HH:MM:SS
Both short and long way |
date +%r
|
09:30:55 PM | The time as HH:MM:SS AA |
date +%m-%d-%y
|
12-02-15 | MM:DD:YY |
date +%m-%d-%Y
|
12-02-2015 | MM:DD:YYYY |
date +%D
|
12/02/2015 | MM/DD/YYYY |
date +"%B %d, %Y"
|
December 2, 2015 | Month DD, YYYY |
See the date man page for the other date and time field options.
Parsing a string timestamp with date
Date can parse a timestamp by passing it into date with the --date
or -d
argument. The specific acceptable format is not well defined by the man page but the command is generally quite forgiving. The given date can contain the time of day, calendar date, timezone, as well as time modifiers.
The time modifier must be at the end of the given date argument and be of this format: MODIFIER_NUMBER UNIT [ago]
. Where unit can be seconds, minutes, hours, days, weeks, months, years. 'ago' reverses the direction of the modifier.
Some examples:
$ date --date="Dec 25, 1889" +%m-%d-%y
12-25-89
$ date --date="12:33 AM 12/25/89 1 day"
Tue Dec 26 12:33:00 MST 1989
$ date --date="12:33 AM 12/25/89 1 year ago"
Sun Dec 25 00:33:00 MST 1988
Working with Unix timestamps
Convert a date to Unix time
## Convert to unix timestamp
$ date --date="Dec 25, 1889" +%s
-2525099168
## Or to nanoseconds by appending 9 zeros
$ date --date="Dec 25, 1998" +%s000000000
914569200000000000
Convert a Unix timestamp to a formatted date string
Pass your unix timestamp to date using the -d @#####
parameter, then use one of the date format strings listed above to format the output.
## Convert from unix timestamp
$ date -d @1603735163 +"%Y %m %d %H:%M:%S"
2020 10 26 11:59:23
Other tasks
Setting the System Clock
Although you really should be using NTP instead, on systems that have no network access, you can set the system clock by running:
# date -s "Mar 30 2020 13:16"
Show time in UTC
Date uses the system's timezone as specified by /etc/localtime
. To force date to use UTC time, one option is to override the TZ environment variable:
$ TZ=UTC0 date
Sat Jul 3 04:49:26 UTC 2021
$ date
Fri Jul 2 22:49:09 MDT 2021
Show the next 3 months of the calendar
$ cal -n 3
July 2021
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
August 2021
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
September 2021
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30