Using date command in Linux

The date command in Linux is used to display the date and time of a system. You can also use it to modify or set the date and time. By using different options with the date command you can print the output in different formats.

In this article, we will discuss how to use the date command with some examples.

Syntax of date command in Linux

The basic syntax of the Linux date command is given below.

date [option]... [+format]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]

You can find a list of options and formats on the date command’s man page.

Usage of date command on Linux

The most basic use of the date command is to display the date and time on a system.

date

As you can see in the output it displays the day of the week, day of the month, month, year, current time, and time zone. By default, the date command is set to the time zone of the operating system.

Display time described by the string

By using option -d or --date you can display the given date string in the format of the date. So let’s see the example:

date --date="05/11/1960"

Please note this doesn’t modify the actual date of the system.

Using date command formatting options

The date command formatting options can be used to display the date and time in a specified format. Format controls start with the % symbol and are substituted by their current values.

Example 1:

date +"Year: %Y, Month: %m, Day: %d"

This will display the given output.

Example 2:

date "+DATE: %D%nTIME: %T"

See the output in the image below.

Example 3:

date +"Week number: %V Year: %y"

This will display:

Similarly, you can use other formatting options with the date command.

How to set or change the date in Linux

You can use --set with the date command to modify the system’s date and time. For example to set the current date and time on your system to 1:40 PM, July 15, 2021 use:

date --set="20210715 01:40PM"

This will change the current date and time to what given here.

Display past or future dates

You can display the past or future dates by using the date command in Linux.

For example:

date --date="5 year ago"

OR

date --date="tomorrow"

Display epoch time

You can use the date command to display epoch time. The epoch or Unix timestamps is the number of seconds that have passed since 1 Jan 1970, at 00:00:00 UTC.

To show the number of seconds from the epoch to the current day, use the %s format control:

date +%s

OR you can use it to display the number of seconds till a specific date.

date -d "1995-02-10" +"%s"

For more, you can check the man page of the date command in your terminal.

man date

Conclusion

I hope now you understand how to use the date command in Linux. Now if you have a query then write us in the comments below.

Leave a Comment