The date Command Explained: Formatting, Arithmetic and Timestamps

The date Command Explained: Formatting, Arithmetic and Timestamps

date prints the date. It also does arithmetic, parses English, converts epoch timestamps in both directions, and is the reason a lot of backup directories do not sort properly.

Format strings

date
# Mon 23 Nov 2026 14:32:07 GMT

date '+%Y-%m-%d'
# 2026-11-23

date '+%Y-%m-%d %H:%M:%S'
# 2026-11-23 14:32:07

date '+%H:%M'
# 14:32

The format starts with +. Without it, date interprets the argument as a time to set.

The specifiers worth remembering:

SpecifierGives
%Y %m %dYear, month, day, zero padded
%H %M %SHour, minute, second, 24-hour
%F%Y-%m-%d, the ISO date
%T%H:%M:%S
%sUnix epoch seconds
%NNanoseconds
%jDay of the year
%u %wWeekday, 1 to 7 Monday-first, or 0 to 6 Sunday-first
%VISO week number
%Z %zTimezone name, numeric offset
%A %BFull weekday and month names
%a %bAbbreviated versions
# the shortcuts, which are worth using
date -I              # 2026-11-23
date -Is             # 2026-11-23T14:32:07+00:00
date -Im             # 2026-11-23T14:32+00:00
date -R              # RFC 5322, for email headers
date -u              # in UTC

ISO 8601 for filenames, always

The single most useful habit in this article.

# sorts correctly, as text
backup-2026-11-23.tar.gz
backup-2026-12-01.tar.gz

# does not
backup-23-11-2026.tar.gz
backup-01-12-2026.tar.gz

ISO 8601 is the only common format that sorts chronologically as a string. Which means ls, globs, and any script reading a directory get the right order for free.

# in a script
tar -czf "backup-$(date -I).tar.gz" /data
tar -czf "backup-$(date +%Y%m%dT%H%M%S).tar.gz" /data

# with seconds, filesystem-safe
logfile="/var/log/myapp-$(date +%Y-%m-%dT%H-%M-%S).log"

Note the hyphens rather than colons in that last one. Colons are legal on Linux filesystems and a nuisance on NTFS or exFAT, and they need quoting in a great many contexts.

Our Btrfs replication guide relies on this sorting property to find the most recent snapshot, which is a concrete example of why it matters.

Relative dates

GNU date parses an unreasonable amount of English.

date -d 'yesterday' -I
date -d 'tomorrow' -I
date -d '3 days ago' -I
date -d '2 weeks' -I
date -d 'next Monday' -I
date -d 'last Friday' -I
date -d '1 month ago' -I
date -d '-1 year' -I

# combined
date -d '2 days ago 14:00' '+%F %T'

# the end of last month, which is awkward any other way
date -d "$(date +%Y-%m-01) -1 day" -I

That last one is the idiom worth keeping: the first of this month minus one day is the last day of last month, which handles February and leap years without you thinking about it.

# beginning and end of today, for log queries
date -d 'today 00:00' '+%F %T'
date -d 'tomorrow 00:00' '+%F %T'

Useful with journalctl, which accepts the same relative expressions directly:

journalctl --since '2 hours ago' --until 'now'
journalctl --since yesterday

Epoch conversion, both directions

# now, as epoch seconds
date +%s
# 1795000327

# epoch to readable, note the @
date -d @1795000327
date -d @1795000327 -Is

# a specific date to epoch
date -d '2026-11-23 14:00' +%s

# milliseconds, since %s is seconds
date +%s%3N

The @ prefix is the part people forget. Without it, date tries to parse the number as a date and produces nonsense or an error.

# convert a log file's epoch timestamps to readable
awk '{ $1 = strftime("%F %T", $1); print }' timestamps.log

# or in a loop
while read -r ts rest; do
    printf '%s %s\n' "$(date -d "@$ts" -Is)" "$rest"
done < timestamps.log

awk’s strftime is much faster than calling date per line, which matters on a large file. Our awk guide covers it.

Arithmetic

Shell arithmetic is integer only, which is the thing to watch.

start=$(date -d '2026-01-01' +%s)
end=$(date -d '2026-11-23' +%s)

echo $(( (end - start) / 86400 ))
# 326

# how long did something take
t0=$(date +%s)
sleep 2
t1=$(date +%s)
echo "took $(( t1 - t0 ))s"

# with sub-second precision
t0=$(date +%s%3N)
sleep 0.5
t1=$(date +%s%3N)
echo "took $(( t1 - t0 ))ms"

Division truncates. (end - start) / 86400 for a period of 1.9 days gives 1, not 2. At boundaries, and across daylight saving transitions where a day is not 86400 seconds, that matters.

# is a certificate expiring soon, a realistic use
expiry=$(openssl x509 -enddate -noout -in cert.pem | cut -d= -f2)
expiry_epoch=$(date -d "$expiry" +%s)
days=$(( (expiry_epoch - $(date +%s)) / 86400 ))
(( days < 30 )) && echo "cert expires in $days days"

Our Let’s Encrypt guide and 64-day certificates post cover why that check is worth automating now.

Timezones, and the script problem

# what is the system set to
timedatectl
cat /etc/timezone 2>/dev/null
readlink -f /etc/localtime

# a specific zone, for one command
TZ='America/New_York' date
TZ='UTC' date
TZ='Asia/Tokyo' date -Is

# list them
timedatectl list-timezones | grep -i london

A script does not inherit your interactive environment. A cron job or systemd service gets the system default, which may not be what you tested with.

# be explicit in scripts
export TZ=UTC
date -Is

Use UTC in logs and filenames on servers. It removes daylight saving ambiguity entirely, and the hour that occurs twice each autumn is a genuine source of confusion in timestamped data.

Our timedatectl guide covers setting the system timezone and keeping the clock correct, which matters more than the formatting.

Setting the clock

# the modern way
sudo timedatectl set-time '2026-11-23 14:00:00'
sudo timedatectl set-timezone Europe/London
sudo timedatectl set-ntp true

# date can set it too, and usually should not
sudo date -s '2026-11-23 14:00:00'

timedatectl rather than date -s. Setting the clock by hand on a machine running NTP means it gets corrected back, and a large jump can upset software that assumes monotonic time. set-ntp true and letting it synchronise is nearly always the right move.

When calling date is too slow

# bash can format time itself, no process spawned
printf '%(%Y-%m-%d)T\n' -1
printf '%(%F %T)T\n' -1

# in a loop, the difference is real
time for i in {1..1000}; do d=$(date -I); done
time for i in {1..1000}; do printf -v d '%(%F)T' -1; done

-1 means now. The printf form is roughly two orders of magnitude faster because it avoids forking.

Irrelevant for a handful of calls. Worth knowing for a loop over thousands of lines, alongside the other patterns in our bash scripting guide.

# also useful: SECONDS, a bash builtin counting since shell start
SECONDS=0
sleep 2
echo "$SECONDS seconds elapsed"
uptime                      # how long since boot
uptime -s                   # when it booted
who -b                      # same, differently

date -d "$(uptime -s)" +%s  # boot time as epoch

# file timestamps
stat -c '%y %n' file        # mtime, human
stat -c '%Y %n' file        # mtime, epoch
touch -d '2026-01-01' file  # set mtime
touch -r reference file     # copy another file's timestamp

Our stat guide covers the three timestamps a file carries and our touch guide covers setting them, which is occasionally needed to make make behave.

Frequently Asked Questions

What is the best date format for filenames?

ISO 8601, which date produces with the -I option or the format string for year, month and day separated by hyphens. It sorts correctly as text, which no other common format does, so a directory of dated files lists in chronological order automatically.

How do I get yesterday or next Monday with date?

Use the -d option with a relative description, such as yesterday, 3 days ago, next Monday or last Friday. GNU date parses a surprisingly wide range of English date expressions, and the result can be formatted like any other date.

How do I convert a Unix timestamp to a readable date?

Pass the number to -d with an @ prefix, so date -d @1700000000. Going the other way, the format string %s prints the epoch seconds for whatever date you gave it, which makes date a converter in both directions.

Why does date show a different time in my script than in my terminal?

Because the timezone comes from the TZ environment variable or the system default, and a cron job or systemd service does not inherit your interactive environment. Set TZ explicitly in the script, or use UTC throughout, which is the safer habit on servers.

What is the difference between date and the shell printf time format?

Calling date starts a process, which costs a few milliseconds each time. Bash can format times itself with printf and a time specification, which matters in a loop running thousands of iterations and is irrelevant for a handful of calls.

How do I calculate the difference between two dates?

Convert both to epoch seconds with the %s format, subtract, then divide by the number of seconds in the unit you want. Shell arithmetic is integer only, so a result in days truncates rather than rounding, which matters at boundaries.