Skip to content
AgileLogics
4 min read

Dates and Times

Prerequisites: Command substitution

The date command prints and calculates dates — essential for timestamped file names, logs, and "older than N days" logic.

Formatting

# illustrative
date
date +%Y-%m-%d
date +"%Y-%m-%d %H:%M:%S"
date +%s
Tue Apr 22 09:30:00 BST 2025
2025-04-22
2025-04-22 09:30:00
1745310600
Code Meaning Code Meaning
%Y year (2025) %H hour (00–23)
%m month (01–12) %M minute
%d day (01–31) %S second
%F %Y-%m-%d %s Unix timestamp
%A weekday name %B month name

%s gives the Unix timestamp (seconds since 1 January 1970, UTC) — convert timestamps with the Unix Epoch Converter.

Date arithmetic (GNU date)

export TZ=UTC
date -d "2025-01-31 + 1 month" +%F
date -d "2025-03-01 - 1 day" +%F
date -d "2025-04-22" +%A
date -d "@0" +"%F %T"
echo $(( ( $(date -d 2025-12-25 +%s) - $(date -d 2025-04-22 +%s) ) / 86400 )) days
2025-03-03
2025-02-28
Tuesday
1970-01-01 00:00:00
247 days
  • -d parses a date description: "yesterday", "+3 days", "next friday".
  • @0 means "timestamp 0".
  • Subtracting timestamps and dividing by 86,400 (seconds per day) gives the number of days between dates.

Note that GNU date rolls 31 January + 1 month over into March. Date arithmetic at month ends is worth testing.

macOS uses BSD date, which has different options: date -v+1d adds a day, and date -j -f parses dates. Install coreutils with Homebrew for GNU date (as gdate).

Timestamped file names

# illustrative
backup="backup-$(date +%Y%m%d-%H%M%S).tar.gz"
echo "$backup"
backup-20250422-093000.tar.gz

Year-month-day ordering sorts chronologically.

Bash 5 also offers $EPOCHSECONDS and printf '%(%F)T' for timestamps without running date.