Date

From Leo's Notes
Revision as of 18:04, 26 October 2020 by Leo (talk | contribs)
This page was last edited on 26 October 2020, at 18:04.

The date unix utility can set or show the current time.

Cheat Sheet

The date utility can be used with a custom format specified by as +<FORMAT>.

Here are some commonly used formats.

Format Output Comment
date Thu Jun 11 14:00:47 MDT 2020 default output
date +%T

date +"%H:%M:%S"

12:34:56 HH:MM:SS

Both short and long way

date +%r 09:30:55 PM 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


Parsing a String Timestamp

Date can parse a timestamp by passing it into date with the --date argument and then formatting the output.

$ date --date="Dec 25, 1889" +%m-%d-%y
12-25-89

Unix Timestamp

Convert Timestamp 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 Unix Time to Formatted Timestamp

## Convert from unix timestamp
$ date -d @1603735163 +"%Y %m %d %H:%M:%S"
2020 10 26 11:59:23

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"