Linux date Command: How to Set, Change, Format Date in Linux

October 10, 2024

Introduction

The Linux date command displays and sets the system date and time. It can format the output in various ways, show the current date, time, or print customized formats using format specifiers. It is very useful for scripts that require timestamp logs or for automating tasks based on specific date and time conditions.

Read on to learn how to use the date command in Linux.

Linux date command - how to set, change, and format date in Linux - a tutorial.

Prerequisites

  • A system running Linux.
  • A user account with root privileges for changing the date.
  • Access to a terminal.

Linux date Command Syntax

The date command has the following syntax:

date [option]... [+format]

Run the date command without options to output the current date and time in the default format.

  • [option] - Optional parameters that allow you to perform specific tasks, such as setting the date or time or formatting the output.
  • [+format] - Format specifiers that customize the output format.

The available options and format specifiers are listed in the sections below.

Linux date Command Options

The options are not mandatory, and they allow you to format, adjust, and display date and time information in various ways.

The following table shows the most common date command options, their descriptions, and a practical example:

OptionDescriptionExample
-d, --date=STRINGDisplays the date and time specified by the given string.date -d "2 days ago"
Outputs the date two days prior.
-r, --reference=FILEDisplays the time the specified file was last modified.date -r /path/to/file
Shows the file's last modified date.
-s, --set=STRINGSets the system date and time (requires superuser privileges).sudo date -s "2024-10-03 14:00:00"
Sets the system date and time.
-u, --utcDisplays the date and time in UTC instead of the local timezone.date -u
Shows the current date and time in UTC.
--helpDisplays the date command help file and prints available options.date --help
Prints the help info file.

Linux date Command Output Format Options

The format specifiers allow you to customize how the date and time are displayed when using the date command.

The following table shows the most common format specifiers, their descriptions, and examples of using them:

FormatDescriptionExample
%YFull year (4 digits).date +"%Y" outputs 2024.
%mMonth (01-12).date +"%m" outputs 10.
%dDay of the month (01-31).date +"%d" outputs 08.
%HHour (00-23, 24-hour format).date +"%H" outputs 14.
%MMinute (00-59).date +"%M" outputs 45.
%SSecond (00-59).date +"%S" outputs 30.
%AFull weekday name.date +"%A" outputs Tuesday.
%aAbbreviated weekday name.date +"%a" outputs Tue.
%BFull month name.date +"%B" outputs October.
%bAbbreviated month name.date +"%b" outputs Oct.
%pAM or PM indicator (12-hour format).date +"%I %p" outputs 02 PM.
%IHour (01-12, 12-hour format).date +"%I" outputs 02.
%TTime in 24-hour format (HH:MM).date +"%T" outputs 14:45:30.
%DDate in MM/DD/YY format.date +"%D" outputs 10/08/24.

Linux date Command Examples

This section provides practical examples of using the date command. See how to get the most out of the command, combine it with other Linux commands, or utilize it in bash scripts to automate your work.

Show Current Date and Time

To show the current system time and date, run the date command without any arguments:

date
Show current date and time in Linux.

The output 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.

Show Specific Date and Time

Use the -d (--date) option to display a specific date and time other than the current one. It allows you to pass a string that represents a date or time in the past, future, or a specific format and then outputs that date.

For example:

date -d "7 days ago"
Showing a specific date in Linux.

You can use the --date option to convert a specific date string to a formatted date. This command does not affect the system's actual date and time values, and it only prints the requested date. For example:

date -d "2024-10-15" +"%A, %B %d, %Y"
Show a specific date using a string and format options.

Note: Learn to create a script using the printf command to display the current date.

Linux date Command Format Options

To format the date command's output, use the control characters preceded by a + sign. Format controls begin with the % symbol and are substituted by their current values.

Here, the %Y character is replaced with the current year, %m with the month, and %d with the day of the month:

date +"Year: %Y, Month: %m, Day: %d"
Formatting the current date in Linux.

Another formatting example shows how to format the date and time:

date "+DATE: %D%nTIME: %T"
Formatting the current date and time.

To see all formatting options, refer to the Linux date Command Output Format Options section above, run date --help, or use the man command.

Set or Change Date in Linux

To set the system date and time with the date command, use the -s (or --set) option followed by the desired date and time in a specific format

For example, to set the date and time to 5:30 PM, May 13, 2010, type:

sudo date --set="20100513 05:30"
Change time and date in Linux using the date command.

Most Linux distributions have the system clock synchronized using the ntp or the systemd-timesyncd services, so be careful when setting the clock manually.

Note: You can also use the set command to change the system clock manually. However, both commands require superuser privileges.

Display Past Dates

Use the --date option to display past dates in Linux. The date command accepts values such as "yesterday", "Friday", "last Friday", "last week", and similar. So, use the following strings to print past dates:

date --date="2 year ago"
Show past dates using the date command.

Use the following command to show yesterday's date:

date --date="yesterday"

Use the following command to see the date and time 10 hours ago:

date --date="10 hour ago"

Display Future Dates

The --date option can also display future dates. Like with past dates, you can type in strings to print upcoming dates.

For example:

date --date="next monday"
Printing future dates using the date command.

You can also use the date command to show the time and date in a specific number of days. For example, to see the time and date in four days, run:

date --date="4 day"

Alternatively, to print tomorrow's date, enter:

date --date="tomorrow"

Display the Date String at Line of File

The --file option prints the date string present at each line of the file. Unlike the --date option, --file can present multiple date strings at each line.

The syntax for using the --file option is:

date --file=[file_name]

Follow the steps below to create an example file and print the dates:

1. Use the cat command to add dates to a file:

cat>> datefile
Oct 15 2024
Nov 1 2024

2. Press Ctrl+D to complete the entry.

3. Run the following command to print the dates using the date command:

date --file=datefile
Print date string at line of a specified file.

The command prints the dates from the input file.

Display Last Modified Timestamp of a Date File

Use the -r option to print the last modification time of a file. For example, the following command prints the last time the hosts file was changed:

date -r /etc/hosts
Print last file modification time.

Override a Time Zone

By default, the date command uses the time zone defined in /etc/localtime. To temporarily use a different time zone in the environment without changing the system's time zone, set the TZ variable to the desired time zone. The syntax is:

TZ='[country]/[city]' date

The [country]/[city] represents the timezone to use. The values correspond to a timezone from the IANA Time Zone database (e.g., TZ='America/Chicago' or TZ='Europe/London').

For example, to switch to New York's time, enter:

TZ='America/New_York' date
Switching time zone using the date command.

To see all available time zones, run the following command:

timedatectl list-timezones

The date command can also show the local time for a different time zone. For example, to display the local time for 4:30 PM next Monday on the Australian east coast, type:

date -d 'TZ="Australia/Sydney" 04:30 next Monday'
Calculate time in different time zone.

Use Unix Epoch Time (Epoch Converter)

You can use the date command as an Epoch converter. Epoch, or Unix timestamps, is the number of seconds that have passed since January 1, 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
show the number of seconds from the epoch to the current day

To see how many seconds passed from the epoch to a specific date, specify the date in the command. For example:

date -d "1984-04-08" +"%s"

Using date with Other Commands

The date command can be combined with other Linux commands to automate tasks, add timestamps, or perform date-based operations. This section provides examples of combining date with other commands and scripts.

Retrieve Date in Preferred Format Using the alias Command

The alias command in Linux allows you to create shortcuts for commonly used commands or sequences of commands. You can use alias to retrieve the date in your preferred format without typing the full command every time.

The syntax for creating an alias is:

alias [alias_name]='date [options]'

For example, to create an alias for the YYYY-MM-DD date format, run:

alias mydate='date +"%Y-%m-%d"'

To use the alias, type in its name in the terminal:

Using the date command with alias.

Using the date Command in Shell Scripts

Another common use of the date command is in shell scripts. Use the command in shell scripts to automate tasks that require time and date information. It is particularly useful for creating logs, timestamping files, scheduling tasks, and performing time-based calculations.

Follow the steps below to create a script that finds and removes files older than one week:

1. Create a new script using a text editor:

nano cleanup.sh

2. Paste the following code and adjust the /path/to/files to the correct directory where you want to delete the files:

#!/bin/bash

seven_days_ago=$(date -d "7 days ago" +"%Y-%m-%d")
find /path/to/files -type f -not -newermt "$seven_days_ago" -exec rm {} \;

echo "Deleted files older than $seven_days_ago"

3. Save and exit the script.

4. Make the script executable:

chmod +x cleanup.sh

5. Run the script:

./cleanup.sh

The script will then find and delete files older than seven days and print the corresponding message.

Using the date Command to Create Files with Dates in the Filename

You can use the date command to create file names that contain the current time and date. It is useful for generating unique filenames, such as log files, backups, or reports, where the date and time provide easy tracking of when a file was created.

For example, use the syntax below to create a backup MySQL file in the format of the current date:

mysqldump database_name > database_name-$(date +%Y%m%d).sql

Alternatively, to create a text file with the touch command and append the current date to the file name, run the following command:

touch file_$(date +"%Y%m%d").txt

Conclusion

This tutorial showed how to use the date command in Linux and provided usage examples.

If you are interested in more date/time configuration options for Linux, read how to set or change timezone/date/time on Ubuntu or how to use JavaScript to get the current date and time.

Was this article helpful?
YesNo
Bosko Marijan
Having worked as an educator and content writer, combined with his lifelong passion for all things high-tech, Bosko strives to simplify intricate concepts and make them user-friendly. That has led him to technical writing at PhoenixNAP, where he continues his mission of spreading knowledge.
Next you should read
How to Use Linux dig Command (DNS Lookup)
May 23, 2024

dig (Domain Information Groper) command is a tool for querying DNS name servers. It is a helpful command for...
Read more
22 Best Linux Text Editors for Programming & Coding
August 8, 2024

A text editor is an application that lets you type text. All Linux distributions come with built-in editors...
Read more
How to Create a File in Linux Using Terminal/Command Line
July 11, 2024

Creating a file in Linux might seem straightforward, but there are some surprising and clever techniques...
Read more
How To Use grep Command In Linux/UNIX
February 29, 2024

This guide details the most useful grep commands for Linux / Unix systems. After going through all the...
Read more