Dates and Timestamps in UNIX/Linux

Niraj Menon Jan 12, 2022
  1. Get the Current Date and Time in Linux
  2. UNIX Time
Dates and Timestamps in UNIX/Linux

Date and time information isn’t quite as visible on the command line as it would be with a graphical version of Linux, but we can certainly get that information with the date command.

This tutorial will explain how to use the date command to get, parse, convert dates and times, and print them in different formats on Linux, assuming a Bash shell command line.

Get the Current Date and Time in Linux

As shown, running date gives us the current date and time, with the time zone.

user@linux:~$ date
Tue 01 Jan 2022 12:00:00 AM +04

The default date-time format will be in the time zone you are located in - in this case, the output of date is for a user whose time zone is Gulf Standard Time, or GMT+04. To print out the date and time in a different format, such as UTC or GMT, or yyyy/mm/dd or dd/mm/yyyy, you can specify that format using special modifiers as follows.

# to print the current date in dd/mm/yyyy format
date +%d-%m-%Y
# to print the current date and time in UTC
date -u
# to print the date and/or time as per IETF RFC3349
date --rfc-3339=seconds
# to print the date and time within a custom string
date +"Today is %D and the time is %I:%M:%S"

UNIX Time

In most UNIX systems, the current time is stored as the time elapsed since a particular moment to simplify, keeping the time as a long integer, called the UNIX epoch. The universally accepted moment for all UNIX systems is January 1st 1970, 12:00:00 AM. This is called a UNIX timestamp and is recognized by all modern UNIX/Linux systems.

For example, if we wish to find the UNIX timestamp for 1st January 2022, we can use the date command.

user@linux:~$ date -d"1 January 2022 12:00 AM" +%s
1640980800

date attempts to parse the string for a formatted date and time (or, if a timestamp is not specified, assumes the time as 12:00 AM) and then prints out the UNIX timestamp form of the given date and/or time. 1640980800 is the exact number of seconds that have elapsed since January 1 1970, 12:00:00 AM.

The converse is also possible, whereby we take a UNIX timestamp and convert it to a date representation. To get back our original date, we can pass the UNIX timestamp as shown to convert it.

user@linux:~$ date -d @1640980800
Sat 01 Jan 2022 12:00:00 AM +04

If we wish, we can also include other parameters to format the date in a specific way, such as UTC or GMT, as explained above.

Related Article - Linux Date