Command linemediumBash

Date and Time Operations

Working with dates, times, formatting, calculations, and timezone conversions.

01

The problem

You need to format dates, calculate time differences, convert timezones, or generate timestamps.

02

The solution

Bash
# Current date and time
date
date '+%Y-%m-%d %H:%M:%S'

# Various date formats
date '+%A, %B %d, %Y'           # Tuesday, January 15, 2024
date '+%Y%m%d_%H%M%S'           # 20240115_143025 (good for backups)
date '+%s'                      # Unix timestamp

# Specific date
date -d '2024-01-15' '+%A'      # Day of week for specific date
date -d 'next Friday'
date -d '2 days ago'
date -d '3 months ago'

# Date arithmetic
date -d 'now + 1 hour'
date -d 'now - 30 minutes'
date -d 'yesterday'
date -d 'tomorrow'

# Convert timestamp to readable date
date -d @1705344000
date -d @1705344000 '+%Y-%m-%d %H:%M:%S'

# Set system date/time (requires root)
sudo date -s '2024-01-15 14:30:00'

# Timezone operations
TZ='America/New_York' date
TZ='Asia/Tokyo' date '+%Y-%m-%d %H:%M:%S %Z'

# List timezones
timedatectl list-timezones

# Set timezone
sudo timedatectl set-timezone America/Los_Angeles

# Show current timezone
timedatectl show --property=Timezone

# NTP synchronization
sudo timedatectl set-ntp true
sudo ntpdate pool.ntp.org

# Calculate time difference
start=$(date +%s)
# ... some operation ...
end=$(date +%s)
echo "Duration: $((end - start)) seconds"

# Sleep with progress
for i in {1..10}; do
  echo -n "."
  sleep 1
done
echo

# Generate sequence of dates
for i in {0..6}; do
  date -d "now + $i days" '+%Y-%m-%d'
done

# Check if daylight saving
date -d '2024-07-01' '+%Z'      # Shows timezone abbreviation

# File timestamp operations
touch -t 202401151430.00 file.txt  # Set specific timestamp
stat file.txt                      # Show file timestamps

# Log with timestamp
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting process..." >> log.txt

# Time command execution
time ls -la
/usr/bin/time -v command         # More detailed timing

03

Put it to work

Example
# Create timestamped backup
timestamp=$(date '+%Y%m%d_%H%M%S')
cp data.db backup/data_${timestamp}.db

# Calculate script runtime
start_time=$(date +%s)
# Your script here
end_time=$(date +%s)
echo "Script took $((end_time - start_time)) seconds"

# Generate log entries
echo "$(date '+%Y-%m-%d %H:%M:%S') - User logged in" >> /var/log/app.log

# Check time in different timezones
echo "NY: $(TZ='America/New_York' date '+%H:%M')"
echo "LN: $(TZ='Europe/London' date '+%H:%M')"
echo "TK: $(TZ='Asia/Tokyo' date '+%H:%M')"

# Create date range for report
for day in {1..7}; do
  date -d "$day days ago" '+%Y-%m-%d'
done

Worth knowing

Use %s for Unix timestamp. date -d accepts flexible natural language. For precision timing, use $EPOCHREALTIME in bash 5.0+. timedatectl for system time management.