Banner of b9601f350fd4e871d07a.jpg

How to Use the date Command in Linux: Complete Guide and Examples


Category: Linux

📅 April 07, 2024   |   👁️ Views: 14

The date command in Linux is a versatile tool used for displaying and formatting date and time information. Whether you need to display the current date and time, manipulate dates, or format them in a specific way, date has you covered. In this tutorial, we'll explore various use cases and formats of the date command to help you become proficient in its usage.

Displaying the Current Date and Time

To display the current date and time, simply run the date command without any arguments:



date


Output:

Wed Apr  6 22:05:24 UTC 2024

Formatting Date and Time

Basic Formatting

You can format the output of date using format specifiers. For example, to display the date in YYYY-MM-DD format:



date '+%Y-%m-%d'


Output:

2024-04-06

Customized Formats

You can customize the output further by combining different format specifiers. For instance:



date '+%A, %B %d, %Y - %H:%M:%S'


Output:

Wednesday, April 06, 2024 - 22:05:24

Manipulating Dates

Adding or Subtracting Days

To manipulate dates by adding or subtracting days, use the --date option:



# Add 1 day to the current date
date --date "+1 days"


Output:

Thu Apr  7 22:05:24 UTC 2024


# Subtract 307 days from the current date
date -d '-307 days'


Output:

Tue May  3 22:05:24 UTC 2023

Displaying Dates Relative to Today

You can display dates relative to today using expressions like "today" or "last Monday":



# Display the date of the last Monday
date -d 'last Monday'


Output:

Mon Apr  3 00:00:00 UTC 2024

Localization

The LC_ALL environment variable can be used to specify the locale for date formatting:



# Display date in Arabic locale
LC_ALL=ar_MA.utf8 date '+%A %d %h %Y, %H:%M'


Output:

الأربعاء 07 إبريل 2024, 22:05

Conclusion

The date command in Linux offers a wide range of functionalities for displaying, formatting, and manipulating dates and times. By mastering its various options and format specifiers, you can efficiently handle date-related tasks in your shell scripts and command-line operations. Experiment with different combinations of options and formats to suit your specific requirements.


← Vim Register Magic: What They Are and How to Use Them Enhancing Quranic Study with a Command-Line Quran Search and Display Script →