0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Date Command in Bash: Syntax and Examples

Use the date command in bash to display or format the current date and time. You can customize the output by adding format options with +FORMAT, where format codes like %Y or %m represent year and month.
📐

Syntax

The basic syntax of the date command is:

  • date: Shows the current date and time.
  • date +FORMAT: Displays the date/time formatted according to FORMAT.
  • date -d "STRING": Shows the date/time for a specified date/time string.

Format codes start with % and represent parts of the date/time, like year, month, day, hour, minute, and second.

bash
date [+FORMAT]
date -d "STRING" [+FORMAT]
💻

Example

This example shows how to display the current date in Year-Month-Day format and how to get the date for tomorrow.

bash
date +"%Y-%m-%d"
date -d "tomorrow" +"%Y-%m-%d"
Output
2024-06-15 2024-06-16
⚠️

Common Pitfalls

Common mistakes include forgetting the + before the format string, which causes the command to print the literal string instead of formatting the date. Another is using unsupported format codes or incorrect date strings with -d.

Always enclose format strings in quotes to avoid shell interpretation issues.

bash
date "%Y-%m-%d"  # Wrong: missing +
date +"%Y-%m-%d"  # Correct

date -d "next week" +"%Y-%m-%d"  # Correct usage of -d
📊

Quick Reference

Format CodeMeaningExample Output
%YYear (4 digits)2024
%mMonth (01-12)06
%dDay of month (01-31)15
%HHour (00-23)14
%MMinute (00-59)30
%SSecond (00-59)05
%aAbbreviated weekdaySat
%AFull weekday nameSaturday

Key Takeaways

Use date +FORMAT to customize date output with format codes.
Always prefix format strings with + and enclose them in quotes.
Use date -d "STRING" to get dates for relative or specific times.
Common format codes include %Y for year, %m for month, and %d for day.
Test your date commands to avoid syntax errors and unexpected outputs.