Timekeeping on computers is essential for many reasons, and spelling out each may take a day. But kidding aside, if you’re looking for effective management of Linux timezones, you’ve come to the right place.
In this tutorial, you’ll explore and learn how you can work with dates, times, and timestamps in Linux. Some are printing the current date and time, calculating future and past dates, working with timezones, and more.
Read on and slay timekeeping like a pro!
Prerequisites
This tutorial comprises hands-on demonstrations. To follow along, you’ll need the following:
- A Linux machine – This tutorial uses Ubuntu 20.04, but any modern Linux distribution will work.
- A text editor – If you don’t have a preferred text editor, you can use nano, which is installed by default on most Linux distributions.
Printing the Current Date and Time with the date
Command
The list of reasons for timekeeping goes on, depending on your needs for your project. But the most common reasons are below:
- System logs use timestamps to catalog when events occurred.
- Software releases are often tied to specific dates.
- Network security tools use time-based analysis to detect anomalies.
- Users rely on accurate time to schedule appointments and meetings.
For any of these reasons, the first thing you may want to perform is print the current date and time. And on Linux, you can accomplish this task with the date and awk commands. But for a start, you’ll run the date command first.
Run the date
command below without parameters to print the current date and time.
date
As you can see below, the command’s output, by default, includes the following:
- The day of the week (Friday)
- The numeric day of the month (10)
- The month name in long format (Friday), and the year.
- The date is followed by the current full-time in 24-hour format and the time zone.
Now, run the following command to view all available options you can use along with the date
command.
date --help
Printing the Current Date in Different Formats
You’ve seen that the date command alone prints the current date and time in full format. But typically, you’ll have to change the format depending on your needs.
The good news is that the date command lets you print the system date and time in different formats — this feature enables you to get better visuals of the current date and time.
1. Run the below command to print the current date only in numeric format (%D).
date "+DATE: %D”
Perhaps you prefer to see the time zone along with the date. In that case, append the %Z option, like in the command below: date “+DATE: %D %Z”
2. Next, run the following command to print the current date in the format of MMM YYYY. The %b option prints the abbreviated month (Nov, Dec, Jan…), while the %Y option prints the current year.
date "+DATE: %b %Y"
3. Now, run the below command to print the date as the long Month (November, December…) (%B), DD (%d), YYYY (%Y).
You can also chain together multiple options to format the output exactly how you want it.
date "+DATE: %B %d,%Y"
4. Lastly, run the same command in step three. But this time, add the %I:%M %p options to print the current time.
date "+DATE: %B %d,%Y %I:%M %p"
Calculating and Printing Future and Past Dates
In real life, you might want to calculate a date that is in the future. Why? Perhaps you’re writing a script to automatically perform tasks on a specific date. If so, calculating future dates using the --date
option will come in handy.
1. Run the below command to calculate the date 40 days from the current date. You can change days to weeks, months, years, etc., as you like.
date --date='40 days'
Below, you can see the calculated full date and time 40 days from the current date.
2. Next, run the same command as you did in step one. But this time, add options (“+%B %d,%Y %I:%M %p”) to change the output format.
date --date='40 days' "+%B %d,%Y %I:%M %p"
3. Now, run the below command, specifying a negative number to calculate dates in the past. The below command calculates the date one year ago from the current date.
date --date='-1 year’
The output below shows the date a year in the past in full default format. But if you like to change the format, you can apply the same format you did in step two.
4. Now, run the command below, using a combination of units (weeks and days) with the –date option. The below command calculates the date two weeks and four days ago from the current date.
date --date='-2 weeks -4 days’
5. Lastly, run the below command to calculate the date next Tuesday.
You can also use other date formats besides the numeric format for the --date
option. For example, you can use full month names, like Tuesday
, or relative time formats like tomorrow
, next
, last
., etc.
date --date='next Tuesday'
Printing Incrementing Dates with a Bash Script
Printing current, past, and future dates work fine with the date command. But did you know you can also write a Bash script to work with timezones, dates, and times? For instance, incrementing the date by day, week, or month.
Incrementing dates is helpful when working with cron jobs that need to run daily, weekly, or monthly.
1. Create a Bash script named date2022.sh with your preferred editor.
2. Add the following code to the file date2022.sh, save the file, and close the editor.
The code below prints the date for each day of the week, starting with today’s date and ending with the following Monday’s date.
DATE=2022-05-30
for i in {0..6}
do
NEXT_DATE=$(date +%m-%d-%Y -d "$DATE + $i day")
echo "$NEXT_DATE"
done
3. Finally, run the below bash command to execute the date2022.sh script
bash date2022.sh
Printing Current Date and Time with the GNU Awk CLI Tool
So far, you’ve seen how to print dates and times in different formats with the date
command, which is good enough. But having more ways to manipulate date and time, be it on the actual system or in a file, is always better.
What’s the other way? The GNU Awk CLI tool. Awk is a powerful text processing tool that can be used for a wide range of tasks. These tasks can be but are not limited to extracting data from log files and manipulating and analyzing text data.
But before you can use the GNU Awk CLI tool, you’ll first have to install it on your machine:
1. Run the apt update command below to update your system package index.
apt update -y
2. Next, run the following apt install command to install the GNU Awk CLI tool.
apt install gawk -y
3. Once installed, run the gawk
command to print
the day of the week (%A
), month (%B
), numeric current date (%d
), and year (%Y
) where the following functions:
- The
strftime
function formats the date and time.
- The systime function returns the current system time in seconds since the Epoch.
gawk 'BEGIN { print strftime("Today is %A, %B %d, %Y.", systime()) }'
Notice how awk allows you to format the output in a human-readable way.
4. Lastly, run the below command to calculate and print the date a month ago. The command below uses the date command with a negative number (-1) to get the first day of the previous month.
awk -v previous_month="$(date -d "`date +%Y%m01` -1 month" +%Y-%m-%d)" '{print previous_month}'
Converting Date Format in a File
Perhaps you have a file containing dates in a format that is incompatible with your current locale. Or the dates in the file are not clear enough to be read by humans. If so, consider using the GNU Awk CLI tool.
Create a file with your preferred text editor and input the following lines to the file where the date format is unclear. Provide the file a name you like, but the CSV file is called test.csv in this example.
1,ABC,SSS,20-OCT-16,4,1,0,5,0,0,0,0
2,DEF,AAA,20-JUL-16,4,1,0,5,0,0,0,0
Now, run the awk command below to extract and convert the date format to a more human-readable format of YY-MM-DD. The -F option sets the field separator as a comma or dash, and the command prints (printf) the date in your desired format.
awk -F'[,-]' '{ printf "%s|20%02d-%02d-%02d,%s\\n", $3, $6, (match("JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC",$5)+2)/3, $4, $10 }' test.csv
As you can see below, the date format is now much clearer.
You’ve seen that awk is a powerful tool that can perform a wide range of tasks, like comparing the date, adding a date field to a file, sorting the dates, etc. But that’s beyond the scope of this article.
Checking the Time Zone Using the grep
Command
Checking the current time zone shouldn’t be a complex tax, and the grep command ensures this statement stays true. The grep command is another powerful text processing tool you can use for a wide range of tasks.
Some tasks that the grep command supports are extracting data from log files and manipulating and analyzing text data. With these features, you can also check your current time zone with the grep command.
Run the following timedatectl command alone to print the current date, time, time zone, and NTP service status on your machine.
timedatectl
As you can see below, the output shows a handful of information about the current date, time, and time zone. This information lets you verify the correct time zone is set on your machine, which also helps ensure you don’t have issues with time synchronization on your network.
Perhaps you like to check the list of time zones before exploring more about the grep command. If so, run the following command: timedatectl list-timezones
Now, run the below command piped to the grep command if you plan to check your machine’s current time zone to perform the following:
- Fetch the date, time, and time zone information from the Linux kernel file (
timedatectl
). - Search and print lines of text that match the
Time zone
text pattern.
timedatectl | grep “Time zone”
As you can see below, the output only shows the current time zone set on your machine.
Conclusion
This tutorial walked you through many practical examples of querying date, time, and Linux timezones. You’ve learned to manipulate date and time format, calculate past and future dates with the date
command. You also ran timedatectl
and grep
commands to check your system’s time zone.
Now, why not write more scripts to automate tasks like calculating past and future dates or converting date formats? Or perhaps create cron jobs to schedule the execution of your scripts?