Creating Custom Date and Time Formats in Linux using the Date Command

Introduction

The date command in Linux is a powerful tool that not only displays current date and time, but allows us to format the output in custom ways. In this article, we will explore how to create custom date and time formats in Linux using the date command.

Custom Formatting

The date command uses various formatting options to output date and time. Some of the most commonly used options are:

%a  abbreviated weekday name, e.g. Sun  
%A  full weekday name, e.g. Sunday
%b  abbreviated month name, e.g. Jan
%B  full month name, e.g. January
%c  preferred date and time representation for the current locale
%d  day of the month (01 to 31)
%H  hour in 24-hour format (00 to 23)
%I hour in 12-hour format (01 to 12)
%m month as a decimal number (01 to 12)
%M minute as a decimal number (00 to 59)
%p either "am" or "pm" according to the given time value
%S second as a decimal number (00 to 59)
%w weekday as a decimal number (0 to 6; Sunday is 0)  
%x  preferred date representation for the current locale, without time
%X  preferred time representation for the current locale, without date
%Y  year as a 4-digit decimal number 
%y year as a 2-digit decimal number

Creating Custom Formats

To create a custom date and time format, we can use the formatting options with the date command. For example, to display the current date in the format dd-mm-yyyy, we can use the following command:

date +%d-%m-%Y

This will output something like:

14-09-2021

Similarly, we can create any custom format using the available formatting options. For example, to display the current time in the format hh:mm:ss, we can use the following command:

date +%H:%M:%S

This will output something like:

15:30:45

Using Quotes

Sometimes, we may need to use special characters in our custom format. In such cases, we need to enclose the format in quotes, so that the special characters are not interpreted by the shell. For example, to display the current time in the format hh_mm_ss, we can use the following command:

date +%H_%M_%S

But if we want to use colon instead of underscore, we need to use quotes like this:

date '+%H:%M:%S'

Conclusion

In conclusion, the date command in Linux is a powerful tool that allows us to create custom date and time formats. By using various formatting options with the date command, we can create any custom format that we want. This can come in handy when we need to display dates and times in specific formats for different applications.