How to Get Date in Bash [2 Methods with Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

The date command in Bash scripting is widely used to retrieve and manipulate dates and times. It offers various formats to print the current, previous, or future dates. This command is useful for tasks like generating timestamps in log files or organizing files based on their creation dates. This article discusses the date command and its application in depth.

Key Takeaways

  • Learning the basic syntax of the date command.
  • Learning about available custom date formats.
  • Arithmetic operations for getting a previous or future date using the date command.
  • Application of date command (Creating timestamps in log files).

Free Downloads

The “date” Command in Bash

One can implement the date command and its options using the following command structure.

Command Syntax >

echo [OPTION]...[+FORMAT]

Useful Options

The date command offers only a few options like -d, -f -s, etc.

You can read this guide to learn more about the date command in Linux.

2 Methods of Displaying Current Date in Bash

Getting the current date is important for any system user. There are two basic ways of getting the current date in Bash. I am going to discuss both methods in this article.

You can read the Comparative Analysis of Methods to find the easy one for you.

Method 1: Using “date” Command in Bash

One can easily get the current date and time by executing the date command from the terminal or by substituting the date command in a Bash script.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a date.sh file in the build-in nano editor:

nano date.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • date.sh: Name of the file.
Creating a .sh file❸ Copy the following script and paste it into nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script in a text editor and save it as .sh file.

# !bin/bash

current_date=$(date)
echo “Today is: $current_date”
EXPLANATION
This script substitutes the date command and stores the output in the current_date variable. Later it displays the output with the message “Today is:”.

❹ Use the following command to make the file executable:

chmod u+x date.sh
EXPLANATION
  • chmod: Changes permissions.
  • u+x: Giving the owner executing permission.
  • date.sh: Name of the script.
Changing file permission❺ Run the script by the following command:

./date.sh

The program prints the current date after the text “Today is: ”.

Method 2: Using the “printf” Command in Bash

Another approach to obtaining the current date in a formatted text is by using the printf command. It allows you to print the current date with specific formatting.

You can follow the Steps of Method 1 to learn about creating and saving shell scripts.

Scripts (printf.sh) >

#!bin/bash

formatted_date=$(printf "%(%Y-%m-%d)T")
echo $formatted_date
EXPLANATION

The script prints the current date in year-month-day format using the printf command. The command is executed and output is stored in the formatted_date variable. Later, it echoed back using the echo command.

Run the script by the following command:

./printf.sh

The image above shows that the program prints the current date which is 2023-06-21.

Comparative Analysis of Methods

Here is a comparative analysis between the above-discussed methods. Take a look at the analysis to determine which method suits your needs best.

Method Advantage Disadvantage
date command
  • Easy to use from the terminal.
  • Offers a huge number of format specifiers.
  • Difficulty in handling time zones.
printf command
  • More versatile.
  • Requires more advanced formatting knowledge.

While both methods are suitable for the task, I personally find the date command more flexible. It provides a wide range of format specifiers, allowing for greater flexibility in displaying dates. Moreover, it allows the printing of both date and time simultaneously.

2 Basic Examples of “date” Command in Bash

The date command is primarily used for getting the current date and time of the system. However, the available options and formats give a user the flexibility to use and manipulate the command in various ways.

Example 1: Getting Past and Future Dates Using Bash Script

The options of the date command are assigned to perform various tasks. For example, one can set a new system time or get a date other than the current date using different options of the date command.

You can follow the Steps of Method 1 to learn about creating and saving shell scripts.

Scripts (dateoption.sh) >

#!bin/bash

# Get yesterday's date
yesterday=$(date -d "yesterday")
echo "Yesterday's date: $yesterday"

# Get date of day before yesterday
b_yesterday=$(date -d "-2 day")
echo "Date of day before yesterday: $b_yesterday"

# Date of the same day in the next week
n_week=$(date -d "next week")
echo "Yesterday's date: $n_week"

# Set a custom date
custom_date="2023-06-30"
sudo date -s "$custom_date"  # Requires root privileges
EXPLANATION

Here the -d command option is used to get yesterday’s date. Later the echo command is used to print yesterday’s date that was saved in the ‘yesterday’ variable.

Later, it prints the day before yesterday using the -d option along with the given parameter “-2 day“.

Afterward, the program uses the -d option once more with the parameter “next week” to show the date of the same day in the next week.

Another command option -s is used to set a new system date and time. This requires root privilege which is given by the sudo command.

Run the script by the following command:

./dateoption.sh

Options in date commandThe program shows yesterday’s date, date of the day before yesterday, and displays a new command prompt for the user to input the password in order to change the system’s date.

Arithmetic Operations Within “date” Command

At this point, you should know a few arithmetic operations that can be performed with the date command. The list below contains a demonstration of such operations.

Command Example Output Details
$ date Wed Jun 21 12:29:10 PM +06 2023 Display the current date.
$ date -d “+5 days” Mon Jun 26 12:29:54 PM +06 2023 Display date after 5 days.
$ date -d “1+tomorrow” Thu Jun 22 01:00:00 AM +06 2023 Display the date of the day after tomorrow.
$ date -d “Jun 18, 2023 +1 week” Sun Jun 25 12:00:00 AM +06 2023 Display date of the day after 1 week from the date Jun 18, 2023.

Example 2: Formatting Date With Various Format Specifiers

The date command offers a huge number of formatting options for printing date and time. The following script demonstrates a few of them. By mentioning the format specifiers, you can customize the output of the date command to suit different date and time representations.

You can follow the Steps of Method 1 to learn about creating and saving shell scripts.

Scripts (dateformat.sh) >

#!/bin/bash

# Get current date and time
current_date=$(date)
echo "Current date and time: $current_date"

# Get date in a specific format
formatted_date=$(date +"%Y-%m-%d")
echo "Formatted date: $formatted_date"

# Get date with day of the week
formatted_date_with_day=$(date +"%A, %B %d, %Y")
echo "Formatted date with day of the week: $formatted_date_with_day"

# Get time in a specific format
formatted_time=$(date +"%H:%M:%S")
echo "Formatted time: $formatted_time"
EXPLANATION

The script begins by capturing the current date and time using the date command and storing it in the current_date variable. Then, it prints the current date and time using echo.

The script continues by formatting the date in a specific format, YYYY-MM-DD, and storing it in the formatted_date variable. This formatted date is also displayed.

Next, it formats the date with the day of the week using %A, %B, %d, and %Y format specifier, representing the full weekday name, month name, day, and year. The output is displayed as before.

Lastly, the script formats the current time as HH:MM:SS and displays it.

Run the script by the following command:

./dateformat.sh

Various date formatIn this image, you can see that the program initially prints the current date and time. Later it prints the date “2023-06-20” which was specified to use the format “%Y-%m-%d“.

In the next part, it prints Tuesday and June in full form which was specified using the specifiers %A and %B. Finally, it prints the current time in HH:MM:SS format.

Format Specifiers of Date Command

The most useful format specifiers of the date command are listed below for your convenience.

Format Description Example code Sample Output
%% A literal $ date +%% %
%a Locale’s weekday name in shorter form; Such as Sun $ date +%a Sun
%A Locale’s full weekday name; Such as Sunday $ date +%A Sunday
%b Locale’s month name in shorter form $ date +%b Jun
%B Locale’s full month name $ date +%B June
%c Locale’s date and time $ date +%c Sun 18 Jun 2023 12:18:40 PM +06
%C century $ date +%C 20
%e Day of month $ date +%e 18
%F Full date; same as %Y-%m-%d $ date +%F 2023-06-18
%g Last two digits of the year of ISO week number $ date +%g 23
%G year of ISO week number $ date +%G 2023
%d Day of month $ date +%d 18
%D Date; same as %m/%d/%y $ date +%D 06/18/23
%H Hour $ date +%H 11
%I Hour $ date +%I 11
%j Day of year $ date +%j 169
%m Month of year $ date +%m 06
%M Minute(00 to 59) $ date +%M 32
%r Locale’s 12-hour clock time $ date +%r 11:12:14 AM
%q Quarter of a year $ date +%q 2
%s seconds since 1970-01-01 00:00:00 UTC $ date +%s 1687068749
%S seconds(00 to 60) $ date +%S 50
%t A tab $ date +%t
%T Time as same as %H:%M:%S $ date +%T 12:10:13
%u Day of week(1 to 7); 1 is Monday $ date +%u 7
%U Week number of the year(0 to 53); Sunday as first day of week $ date +%U 25
%V ISO week number of the year(0 to 53); Monday as the first day of week $ date +%V 24
%w Day of week(0 to 6); 0 is sunday $ date +%w 0
%W Week of year(0 to 53); Monday as firstday of the week $ date +%W 24
%x Locale’s date representation $ date +%x 06/18/2023
%X Locale’s time representation $ date +%X 12:04:10 PM
%y Last two digits of year $ date +%y 23
%Y Full year $ date +%Y 23
%z +hhmm numeric time zone $ date +%z +0600
%:z +hh:mm numeric time zone $ date +%:z +06:00
%::z +hh:mm:ss numeric time zone $ date +%::z +06:00:00
%:::z numeric time zone with : to necessary precision(+06, -05:30) $ date +%:::z +06
%Z Time zone abbreviation $ date +%Z +06

Creating Timestamps for Log Files Using “date” Command

Timestamps of log files are important to notify users about the last modification time of a file. One can use the date command to create a Bash program that will append timestamps on a log file after each modification.

You can follow the Steps of Method 01 to learn about creating and saving shell scripts.

Scripts (timestamp.sh) >

#!/bin/bash

# Get the current timestamp
timestamp=$(date +"%Y-%m-%d %H:%M:%S")

# Log message
log_message="This is a log message."

# Append the timestamp and log message to the log file
echo "$timestamp $log_message" >> log_file.txt
EXPLANATION

This script captures the current time and date using the date command and formats it as YYYY-MM-DD HH:MM:SS. The formatted timestamp is then stored in the timestamp variable. The final line appends the timestamp and log message to a log file.

Run the script by the following command:

./timestamp.sh

Creating a timestampThe output shows that the script adds a timestamp on the log_file.txt. When visualizing the file using the cat command, it shows 2023-06-20 17:40:21 timestamp is appended with the log message.

Conclusion

In conclusion, the date command is very useful for finding present, past, and future dates. One can print those in many formats. Hope this article will help you in printing dates in whatever formats you like.

People Also Ask

Get current time in seconds since the epoch on Linux?
Use +%s format to print the current time in seconds since the epoch on Linux that starts counting from 1970-01-01 00:00:00.
How to get CST date in Bash
To get the CST (Central Standard Time) time use  TZ=<Your Timezone> before the date command. Like- todaysDate=$(TZ=CST6CDT date). Otherwise, it will automatically print the UTC(Coordinated Universal Time).
Can I get a past date using the date command?
Yes, you can. Use “-n days” to print the date of n days before the current date.

Related Articles


<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial

Rate this post
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment