Linux Date Command: Complete Guide and Reference
Table of Contents
- [Introduction](#introduction) - [Basic Syntax](#basic-syntax) - [Command Options](#command-options) - [Format Specifiers](#format-specifiers) - [Basic Usage Examples](#basic-usage-examples) - [Advanced Usage Examples](#advanced-usage-examples) - [Date Arithmetic](#date-arithmetic) - [Timezone Operations](#timezone-operations) - [Practical Applications](#practical-applications) - [Common Use Cases](#common-use-cases) - [Troubleshooting](#troubleshooting) - [Best Practices](#best-practices)Introduction
The date command in Linux is a versatile utility used to display and manipulate system date and time information. It serves multiple purposes including displaying current date/time, formatting output in various ways, performing date calculations, and setting system time (with appropriate privileges). This command is essential for system administration, scripting, logging, and various automation tasks.
The date command reads the system clock and can display time in numerous formats, work with different timezones, and perform arithmetic operations on dates. It's particularly valuable in shell scripting for creating timestamps, scheduling tasks, and generating time-based file names.
Basic Syntax
`bash
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
`
Core Components
| Component | Description | Required |
|-----------|-------------|----------|
| date | Base command | Yes |
| OPTION | Command line flags and options | No |
| FORMAT | Output format specification preceded by + | No |
| MMDDhhmm | Date/time setting format | No |
Command Options
Primary Options Table
| Option | Long Form | Description | Example |
|--------|-----------|-------------|---------|
| -d | --date=STRING | Display time described by STRING | date -d "tomorrow" |
| -f | --file=DATEFILE | Process dates from file | date -f dates.txt |
| -r | --reference=FILE | Display last modification time of FILE | date -r /etc/passwd |
| -s | --set=STRING | Set system date/time | date -s "2024-01-01 12:00:00" |
| -u | --utc, --universal | Display or set UTC time | date -u |
| -R | --rfc-2822 | Output RFC 2822 compliant date | date -R |
| -I | --iso-8601 | Output ISO 8601 date format | date -I |
| | --help | Display help information | date --help |
| | --version | Display version information | date --version |
Detailed Option Explanations
-d, --date=STRING
This option allows you to display the date and time specified by STRING instead of the current date. STRING can be in various formats including relative dates like "yesterday", "next Monday", "2 hours ago", or absolute dates.
-f, --file=DATEFILE
Processes multiple date strings from a file, with each line treated as a separate date specification. Useful for batch processing of dates.
-r, --reference=FILE
Shows the last modification timestamp of the specified file rather than the current system time. This is equivalent to stat -c %y filename.
-s, --set=STRING
Sets the system date and time. Requires root privileges. The STRING can be in various formats but must be unambiguous.
-u, --utc, --universal
Forces the command to work with Coordinated Universal Time (UTC) instead of the local timezone.
Format Specifiers
Date Format Codes
| Code | Description | Example Output |
|------|-------------|----------------|
| %a | Abbreviated weekday name | Mon |
| %A | Full weekday name | Monday |
| %b | Abbreviated month name | Jan |
| %B | Full month name | January |
| %c | Complete date and time | Mon 01 Jan 2024 12:00:00 PM EST |
| %d | Day of month (01-31) | 01 |
| %D | Date in mm/dd/yy format | 01/01/24 |
| %e | Day of month, space padded (1-31) | 1 |
| %F | Full date in YYYY-MM-DD format | 2024-01-01 |
| %g | 2-digit year for ISO week | 24 |
| %G | 4-digit year for ISO week | 2024 |
| %h | Same as %b | Jan |
| %H | Hour in 24-hour format (00-23) | 12 |
| %I | Hour in 12-hour format (01-12) | 12 |
| %j | Day of year (001-366) | 001 |
| %k | Hour in 24-hour format, space padded (0-23) | 12 |
| %l | Hour in 12-hour format, space padded (1-12) | 12 |
| %m | Month number (01-12) | 01 |
| %M | Minute (00-59) | 00 |
| %n | Newline character | |
| %N | Nanoseconds (000000000-999999999) | 123456789 |
| %p | AM or PM | PM |
| %P | am or pm (lowercase) | pm |
| %r | 12-hour time format | 12:00:00 PM |
| %R | 24-hour time format HH:MM | 12:00 |
| %s | Seconds since Unix epoch | 1704110400 |
| %S | Second (00-60) | 00 |
| %t | Tab character | |
| %T | 24-hour time format HH:MM:SS | 12:00:00 |
| %u | Day of week (1-7, Monday=1) | 1 |
| %U | Week number, Sunday first (00-53) | 01 |
| %V | ISO week number (01-53) | 01 |
| %w | Day of week (0-6, Sunday=0) | 1 |
| %W | Week number, Monday first (00-53) | 01 |
| %x | Locale's date representation | 01/01/2024 |
| %X | Locale's time representation | 12:00:00 PM |
| %y | 2-digit year (00-99) | 24 |
| %Y | 4-digit year | 2024 |
| %z | Timezone offset from UTC | -0500 |
| %Z | Timezone abbreviation | EST |
| %% | Literal % character | % |
Time Format Examples Table
| Format String | Output Example | Use Case |
|---------------|----------------|----------|
| +%Y-%m-%d | 2024-01-01 | ISO date format |
| +%d/%m/%Y | 01/01/2024 | European date format |
| +%m/%d/%Y | 01/01/2024 | American date format |
| +%Y%m%d_%H%M%S | 20240101_120000 | Filename timestamps |
| +%A, %B %d, %Y | Monday, January 01, 2024 | Readable long format |
| +%r | 12:00:00 PM | 12-hour time |
| +%T | 12:00:00 | 24-hour time |
| +%s | 1704110400 | Unix timestamp |
Basic Usage Examples
Displaying Current Date and Time
`bash
Display current date and time in default format
dateOutput: Mon Jan 1 12:00:00 EST 2024
Display current date in ISO format
date -IOutput: 2024-01-01
Display current date and time in ISO format with time
date -IsecondsOutput: 2024-01-01T12:00:00-05:00
Display current UTC time
date -uOutput: Mon Jan 1 17:00:00 UTC 2024
`Custom Format Examples
`bash
Display date in YYYY-MM-DD format
date +%Y-%m-%dOutput: 2024-01-01
Display time in HH:MM:SS format
date +%H:%M:%SOutput: 12:00:00
Display full weekday and month names
date +"%A, %B %d, %Y"Output: Monday, January 01, 2024
Create a timestamp for filenames
date +%Y%m%d_%H%M%SOutput: 20240101_120000
Display date with timezone information
date +"%Y-%m-%d %H:%M:%S %Z"Output: 2024-01-01 12:00:00 EST
`Reference File Timestamps
`bash
Show last modification time of a file
date -r /etc/passwdOutput: Wed Dec 20 10:30:45 EST 2023
Show file timestamp in custom format
date -r /etc/passwd +"%Y-%m-%d %H:%M:%S"Output: 2023-12-20 10:30:45
Compare file modification time with current time
echo "File: $(date -r /etc/passwd +%s)" echo "Now: $(date +%s)"Output: File: 1703088645
Now: 1704110400
`Advanced Usage Examples
Date Arithmetic and Relative Dates
`bash
Display tomorrow's date
date -d "tomorrow"Output: Tue Jan 2 12:00:00 EST 2024
Display yesterday's date
date -d "yesterday"Output: Sun Dec 31 12:00:00 EST 2023
Display date 1 week ago
date -d "1 week ago"Output: Mon Dec 25 12:00:00 EST 2023
Display date 30 days from now
date -d "30 days"Output: Wed Jan 31 12:00:00 EST 2024
Display next Monday
date -d "next Monday"Output: Mon Jan 8 12:00:00 EST 2024
Display last Friday
date -d "last Friday"Output: Fri Dec 29 12:00:00 EST 2023
`Complex Date Calculations
`bash
Add 2 hours and 30 minutes to current time
date -d "2 hours 30 minutes"Output: Mon Jan 1 14:30:00 EST 2024
Subtract 3 months from current date
date -d "3 months ago"Output: Fri Oct 1 12:00:00 EDT 2023
Calculate date 90 days ago
date -d "90 days ago" +%Y-%m-%dOutput: 2023-10-03
Find what day of week a specific date was
date -d "2023-12-25" +%AOutput: Monday
Calculate days between two dates (using Unix timestamps)
date1=$(date -d "2024-01-01" +%s) date2=$(date -d "2024-01-31" +%s) echo $(( (date2 - date1) / 86400 )) daysOutput: 30 days
`Working with Specific Dates
`bash
Display specific date
date -d "2024-06-15"Output: Sat Jun 15 00:00:00 EDT 2024
Display specific date and time
date -d "2024-06-15 14:30:00"Output: Sat Jun 15 14:30:00 EDT 2024
Parse various date formats
date -d "June 15, 2024"Output: Sat Jun 15 00:00:00 EDT 2024
date -d "15/06/2024"
Output: Sat Jun 15 00:00:00 EDT 2024
date -d "2024-06-15T14:30:00"
Output: Sat Jun 15 14:30:00 EDT 2024
`Date Arithmetic
Arithmetic Operations Table
| Operation | Syntax Example | Description |
|-----------|----------------|-------------|
| Add days | date -d "+5 days" | Add 5 days to current date |
| Subtract days | date -d "-10 days" | Subtract 10 days from current date |
| Add weeks | date -d "+2 weeks" | Add 2 weeks to current date |
| Add months | date -d "+3 months" | Add 3 months to current date |
| Add years | date -d "+1 year" | Add 1 year to current date |
| Add hours | date -d "+6 hours" | Add 6 hours to current time |
| Add minutes | date -d "+45 minutes" | Add 45 minutes to current time |
| Add seconds | date -d "+30 seconds" | Add 30 seconds to current time |
Complex Arithmetic Examples
`bash
Combine multiple operations
date -d "next Monday +2 weeks -1 day"Output: Sun Jan 21 12:00:00 EST 2024
Calculate end of current month
date -d "$(date +%Y-%m-01) +1 month -1 day"Output: Wed Jan 31 00:00:00 EST 2024
Calculate beginning of current year
date -d "$(date +%Y-01-01)"Output: Mon Jan 1 00:00:00 EST 2024
Calculate last day of previous year
date -d "$(date +%Y-01-01) -1 day"Output: Sun Dec 31 00:00:00 EST 2023
`Business Day Calculations
`bash
Find next business day (skip weekends)
next_day=$(date -d "tomorrow") while [[ $(date -d "$next_day" +%u) -gt 5 ]]; do next_day=$(date -d "$next_day +1 day") done echo "Next business day: $next_day"Calculate 30 business days from now (excluding weekends)
business_days=0 current_date=$(date) while [[ $business_days -lt 30 ]]; do current_date=$(date -d "$current_date +1 day") if [[ $(date -d "$current_date" +%u) -le 5 ]]; then ((business_days++)) fi done echo "30 business days from now: $current_date"`Timezone Operations
Timezone Environment Variable
`bash
Display time in different timezones using TZ environment variable
TZ='America/New_York' dateOutput: Mon Jan 1 12:00:00 EST 2024
TZ='Europe/London' date
Output: Mon Jan 1 17:00:00 GMT 2024
TZ='Asia/Tokyo' date
Output: Tue Jan 2 02:00:00 JST 2024
TZ='UTC' date
Output: Mon Jan 1 17:00:00 UTC 2024
`Timezone Conversion Examples
`bash
Convert current time to different timezones
echo "Local: $(date)" echo "UTC: $(TZ='UTC' date)" echo "Tokyo: $(TZ='Asia/Tokyo' date)" echo "London: $(TZ='Europe/London' date)" echo "LA: $(TZ='America/Los_Angeles' date)"Output:
Local: Mon Jan 1 12:00:00 EST 2024
UTC: Mon Jan 1 17:00:00 UTC 2024
Tokyo: Tue Jan 2 02:00:00 JST 2024
London: Mon Jan 1 17:00:00 GMT 2024
LA: Mon Jan 1 09:00:00 PST 2024
`Common Timezone Codes Table
| Timezone | Code | Example Output | |----------|------|----------------| | Eastern Standard Time | EST | Mon Jan 1 12:00:00 EST 2024 | | Pacific Standard Time | PST | Mon Jan 1 09:00:00 PST 2024 | | Greenwich Mean Time | GMT | Mon Jan 1 17:00:00 GMT 2024 | | Central European Time | CET | Mon Jan 1 18:00:00 CET 2024 | | Japan Standard Time | JST | Tue Jan 2 02:00:00 JST 2024 | | Coordinated Universal Time | UTC | Mon Jan 1 17:00:00 UTC 2024 |
Practical Applications
Log File Management
`bash
Create log files with timestamps
echo "Application started" >> app_$(date +%Y%m%d).logRotate logs daily
log_file="application_$(date +%Y-%m-%d).log" echo "$(date): System backup completed" >> "$log_file"Archive old logs (older than 30 days)
find /var/log -name "*.log" -mtime +30 -exec rm {} \;Create backup with timestamp
backup_name="backup_$(date +%Y%m%d_%H%M%S).tar.gz" tar -czf "$backup_name" /important/data/`System Administration Scripts
`bash
#!/bin/bash
System monitoring script with timestamps
echo "=== System Status Report ===" echo "Generated: $(date)" echo "Uptime: $(uptime)" echo "Disk Usage:" df -h echo "Memory Usage:" free -h echo "Current Users:" who echo "Report completed at: $(date)"
Schedule maintenance window
maintenance_start=$(date -d "next Sunday 2:00 AM") maintenance_end=$(date -d "next Sunday 4:00 AM") echo "Next maintenance window: $maintenance_start to $maintenance_end"`File Organization
`bash
Organize files by date
for file in *.txt; do file_date=$(date -r "$file" +%Y-%m) mkdir -p "$file_date" mv "$file" "$file_date/" doneClean up temporary files older than 7 days
find /tmp -type f -mtime +7 -deleteCreate dated directories
mkdir "project_$(date +%Y%m%d)" mkdir "reports_$(date +%Y_%m)" mkdir "archive_$(date +%Y)"`Common Use Cases
Database Operations
`bash
MySQL backup with timestamp
mysqldump -u user -p database > "db_backup_$(date +%Y%m%d_%H%M%S).sql"PostgreSQL backup
pg_dump database > "pg_backup_$(date +%Y-%m-%d).sql"Log database operations
echo "$(date '+%Y-%m-%d %H:%M:%S'): Database backup completed" >> db.log`Web Server Log Analysis
`bash
Analyze today's Apache logs
grep "$(date +%d/%b/%Y)" /var/log/apache2/access.log | wc -lFind errors from last hour
grep "$(date -d '1 hour ago' '+%d/%b/%Y:%H')" /var/log/apache2/error.logRotate web server logs
mv /var/log/nginx/access.log "/var/log/nginx/access_$(date +%Y%m%d).log" systemctl reload nginx`Cron Job Scheduling
`bash
Add timestamp to cron job output
0 2 * /path/to/script.sh >> /var/log/cron_$(date +\%Y\%m).log 2>&1Daily cleanup script
#!/bin/bash echo "$(date): Starting daily cleanup"Cleanup operations here
echo "$(date): Daily cleanup completed"Weekly report generation
0 0 0 /usr/local/bin/generate_report.sh "$(date +\%Y-\%W)"`Troubleshooting
Common Issues and Solutions
Issue: Date command not found
`bash
Check if date is installed
which dateOutput: /bin/date
If not found, install coreutils package
On Debian/Ubuntu:
sudo apt-get install coreutilsOn RHEL/CentOS:
sudo yum install coreutils`Issue: Permission denied when setting date
`bash
Setting system date requires root privileges
sudo date -s "2024-01-01 12:00:00"Check current user privileges
id whoami`Issue: Incorrect timezone display
`bash
Check current timezone
timedatectl status cat /etc/timezoneSet timezone
sudo timedatectl set-timezone America/New_YorkVerify timezone change
date`Issue: Date parsing errors
`bash
Invalid date format
date -d "invalid date"Output: date: invalid date 'invalid date'
Use proper format
date -d "2024-01-01" date -d "January 1, 2024" date -d "01/01/2024"`Debugging Date Issues
`bash
Verbose output for debugging
date --debug -d "next Friday"Check system clock synchronization
timedatectl statusVerify NTP synchronization
ntpq -pCheck hardware clock
sudo hwclock --show`Best Practices
Scripting Best Practices
`bash
Always use consistent date formats in scripts
LOG_DATE=$(date +%Y-%m-%d) TIMESTAMP=$(date +%Y%m%d_%H%M%S)Use ISO format for portability
DATE_ISO=$(date -I) DATETIME_ISO=$(date -Iseconds)Store timestamps in variables for consistency
START_TIME=$(date +%s)... script operations ...
END_TIME=$(date +%s) DURATION=$((END_TIME - START_TIME)) echo "Script completed in $DURATION seconds"`Performance Considerations
`bash
Avoid calling date multiple times in loops
current_date=$(date +%Y-%m-%d) for file in *.log; do mv "$file" "${current_date}_${file}" doneUse date arithmetic instead of multiple calls
Instead of:
tomorrow=$(date -d "$(date) +1 day")Use:
tomorrow=$(date -d "tomorrow")`Security Considerations
`bash
Validate date input in scripts
validate_date() { if date -d "$1" >/dev/null 2>&1; then return 0 else echo "Invalid date: $1" return 1 fi }Use quotes around date strings
user_date="$1" if validate_date "$user_date"; then processed_date=$(date -d "$user_date" +%Y-%m-%d) fi`Portability Tips
`bash
Use standard format specifiers for portability
Avoid GNU-specific extensions when possible
portable_date=$(date +%Y-%m-%d)Test date operations on target systems
Some systems may have different date implementations
Use UTC for consistent behavior across systems
utc_timestamp=$(date -u +%s)`The date command is an essential tool for Linux system administration and scripting. Its flexibility in formatting, timezone handling, and date arithmetic makes it invaluable for various tasks from simple timestamp generation to complex date calculations. Understanding its capabilities and proper usage patterns will significantly enhance your ability to work with dates and times in Linux environments.