date Command in Linux: View, Format, and Set Date and Time
The date command in Linux can be used to display the date or set the system date.
The most common options are:
- -d string Shows the time in a specific format
- -u Shows or sets the time in UTC (Coordinated Universal Time) format
- -s Sets the time
Coordinated Universal Time, abbreviated UTC, also known as civil time, is the reference time zone from which all other time zones in the world are calculated.
See the examples:
$ dateSat 19 Oct 2019 01:13:02 PM -03
The "-u" option shows the time in UTC format:
$ date -uSat 19 Oct 2019 04:13:45 PM UTC
The date command allows displaying a date in various formats:
%D: mm/dd/yy.
%d: Day of the month (01 to 31).
%a: Abbreviated weekday (Sun, Mon ... Sat).
%A: Full weekday name (Sunday, Monday...Saturday).
%h or %b: Abbreviated month (Jan, Feb... Dec).
%B: Full month name (January... December).
%m: Month as number (01 to 12).
%y: Last two digits of the year (00 to 99).
%Y: Four-digit year (2019).
%T: Time in 24-hour format HH:MM:SS.
%H: Hour.
%M: Minute.
%S: Second.
%j: Day of the year (122)
%u: Weekday (1... 7) - 7 is Sunday.
%w: Weekday (0... 6) - 0 is Sunday.
%F: Format YYYY-MM-DD
Examples:
$ date +'Hoje é %A, %d de %B de %Y, o %j dia do ano, as %H:%M'Hoje é Saturday, 02 de November de 2019, o 292 dia do ano, as 14:14
This example looks odd, because it shows the date in English locale with a Portuguese sentence.
To change the locale and display everything in Portuguese, we can change the LC_ALL variable:
$ export LC_ALL=pt_BR.UTF-8
When running the date command again, the date will be in Portuguese:
$ date +'Hoje é %A, %d de %B de %Y, o %j dia do ano, as %H:%M'Hoje é sábado, 02 de Novembro de 2019, o 292 dia do ano, as 14:15
Changing the date format can be useful to use in a variable for a script:
#!/bin/bashecho "backup dos dados"export DATA=$(date +'%F-%H%M%S')tar cvzf /home/uira/backup-$DATA.tar.gz /etc
The script above writes the date in YYYY-MM-DD-HHMMSS format to the DATA variable. It then uses the variable as part of the name for a tar file that backs up the /etc directory. The result of execution will be a file backup-2019-10-19-142339.tar.gz.
Note that the output of a command can be used in a variable if it's enclosed in $( command ).
Changing the Date in Linux
The date command can also be used to change the system clock date. In this example, I changed the system date to my birthday:
# date +%Y%m%d -s "2019-05-11"20190511
$ datesáb mai 11 00:00:01 -03 2019
The TZ variable changes the date and time shown by the date command to the time zone.
Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here. Also check out our content with all the main processes and commands in Linux.
Liked it? Share
That was just one piece. The course teaches the whole path — from your first command to exam day.