How to Work with Date and Time in Bash Using date Command

Date command is an external bash program that allows to set or display system date and time. It also provides several formatting options. Date command is installed in all Linux distros by default.

$ which date
$ type -a date
Find Date Command Location
Find Date Command Location

Type date command in terminal which will display current date and time.

$ date
Check Date in Linux
Check Date in Linux

Change Linux System Date and Time

Using date command, system date, time and timezone can be modified and the change has to be synced with the hardware clock.

$ date --set="Thu Nov 12 13:06:59 IST 2020"
$ hwclock --systohc
Set Linux System Date and Time
Set Linux System Date and Time

Formatting Options

A good place to get the list of formatting options will be the man page.

$ man date

Let’s see some of the most common formatting options that we will use.

  • To apply formatting use “+ followed by “formatter“.
  • To get a list of formatting options for GNU\LINUX take a look at the linked man page.
  • To get a list of formatting options for BSD take a look at the linked man page.

The two important parts of the date command is using Format +% and –date option.

Now let’s apply some formatting on the date command. To apply formatting, add plus sign (+) followed by %formatter as shown in examples.

Handling Date in Linux

Let’s take a look at how to use date related formatters in a simple shell script called ‘date.sh‘.

# PRINT YEAR,MONTH,DAY AND DATE...

echo "We are in the year = $(date +%Y)"
echo "We are in the year = $(date +%y)"

# Difference between %Y and %y is %Y will print 4 digits while %y will print the last 2 digits of the year.

echo "We are in the month = $(date +%m)"
echo "We are in the month = $(date +%b)"
echo "We are in the month = $(date +%B)"

# Difference between %B and %b is, %B will print full month name while %b will print abbreviated month name.

echo "Current Day of the month = $(date +%d)"

echo "Current Day of the week = $(date +%A)"
echo "Current Day of the week = $(date +%a)"

# Difference between %A and %a is, %A will print full Weekday name while %a will print abbreviated weekday name.

# Instead of formatting to get the date, we can use %D which will print the date as %m/%d/%y or %F which prints in %Y-%M-%d format.

echo "Date using %D = $(date +%D)"
echo "Date using %F = $(date +%F)"
Find Date and Time using Script
Find Date and Time using Script

Handling Time in Linux

Let’s take a look at how to use time related formatters in a simple shell script called ‘time.sh‘.

# PRINT HOURS, MINS, SECONDS, NANO SECONDS

echo Hours = $(date +%H)
echo Minutes = $(date +%M)
echo Seconds = $(date +%S)
echo Nanoseconds = $(date +%N)
echo Epoch Time = $(date +%s)

echo "current time = $(date +%H:%M:%S:%N)"

# can also use %T which displays Time in HH:MM:SS format.

echo "current time in 24 hour format = $(date +%T)"

# can also use %r to display time in 12 hour format.

echo "current time in 12 hour format = $(date +%r)"
Find Time in Linux Using Script
Find Time in Linux Using Script

With –date or -d Flag

With --date or -d flag input can be passed as string and date command knows to handle it smartly.

Let’s see some examples to understand how it works.

# Print yesterday's date and time.
echo "Yesterday = $(date -d "Yesterday")"

# Print Tomorrow date and time.
echo "tomorrow = $(date -d "tomorrow")"

# Find what is the date and time before 10 days from now.
echo "Before 10 days = $(date -d "tomorrow -10 days")"

# Find last month and next month
echo "Last month = $(date -d "last month" "%B")"
echo "Next month = $(date -d "next month" "%B")"

# Find last year and next year
echo "Last Year = $(date -d "last year" "+%Y")"
echo "Next Year = $(date -d "next year" "+%Y")"

# Forecast the weekday
echo "2 days away from today and it comes on weekdays? = $(date -d "Today +2 days" "+%A")
Check Date Using Formatting
Check Date Using Formatting

Common Operations

calculate the number of days between 2 given dates.

$ echo $(( ( $(date -d "2020-11-10" "+%s") - $(date -d "2020-11-01" "+%s") ) / 86400))

Find the given year is leap year or not.

$ for y in {2000..2020}; do date -d $y-02-29 &>/dev/null && echo $y is leap year; done
Find Leap Year in Linux
Find Leap Year in Linux

Assigning output of date command to a variable.

$ TODAY=$(date +%Y-%m-%d)
OR
$ TODAY1=$(date +%F)
$ echo $TODAY 
$ echo $TODAY1
Assign Date to Variable
Assign Date to Variable

Create log files with the date added to the filename.

Adding date and time while creating log files, backup, or text files is a common operation that we will encounter most often. Let’s take an example, to take a backup, we have created a shell script.

This script will take a backup from 00:00 to 23:59 and scheduled to run daily at 00:00 of the next day. We want to create log files with yesterday’s date format.

CUSTOM_FORMAT=$(date --date "Yesterday" "+%d-%y-%H:%M")
LOG_FILE=/var/log/custom_application/application_${CUSTOM_FORMAT}.log
echo "Script started" >>  ${LOG_FILE}
...
CODE BLOCKS
...
echo "Script completed" >> ${LOG_FILE}

That’s it for this article. In this article, we have seen how to use bash date and time in Linux. Let us know your feedback.

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

Karthick
A passionate software engineer who loves to explore new technologies. He is a public speaker and loves writing about technology, especially about Linux and open source.

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

2 Comments

Leave a Reply
  1. Thanks a lot, it’s a very useful article.

    “echo $(( ( $(date -d “2020-11-10” “+%s”) – $(date -d “2020-11-01” “+%s”) ) / 86400))”

    How do you calculate this number 86400, please?

    Reply
  2. date +s is the number of seconds since 1 Jan 1970. Dividing the result by seconds per day will indicate the day count, the number of days since 1 Jan 1970. Why is this useful?

    I want to run something every 11 days from the previous day. I determine the day-count (number of days) since 1 Jan 1970, add 11, and store the result in a file. When I run a cronjob to check today’s daycount against the saved value, subtraction can tell me if the period has expired or the number of days to go. If by chance, I did not boot my computer for 15 days, the day-count subtraction will be negative, and I will run my job, and then set the day-count to 11 past today.

    Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.