Unix timestamps in Bash

Get the current epoch time and convert between timestamps and dates in Bash. Every snippet below is copy-ready.

// note

GNU date supports %3N and -d; macOS date uses -r and -j -f.

now.sh · current timestamp
now=$(date +%s)        # seconds
now_ms=$(date +%s%3N)  # milliseconds (GNU date)
timestamp → date
ts=1700000000
date -u -d "@$ts" +"%Y-%m-%dT%H:%M:%SZ"
# macOS: date -u -r "$ts" +"%Y-%m-%dT%H:%M:%SZ"
date → timestamp
date -u -d "2023-11-14 22:13:20" +%s
# macOS: date -u -j -f "%Y-%m-%d %H:%M:%S" "2023-11-14 22:13:20" +%s
// current epoch

— seconds since 1970-01-01T00:00:00Z.

Watch out for these

  • Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
  • Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
  • Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.

Reference: https://www.gnu.org/software/coreutils/manual/html_node/date-invocation.html

advertisement