Unix Timestamp in Bash

GNU date and BSD/macOS date take different flags — the most common portability trap in shell scripts.

Need to convert one value rather than write code? Use the interactive converter — it handles every unit and time zone without leaving your browser.

Current Unix timestamp

date +%s          # 1710050400        seconds
date +%s%3N       # 1710050400123     milliseconds (GNU only)
printf '%(%s)T\n' -1    # bash 4.2+, no subprocess

Timestamp to date (GNU / Linux)

date -d @1710050400
date -u -d @1710050400 +'%Y-%m-%d %H:%M:%S'
TZ='Asia/Kolkata' date -d @1710050400 +'%Y-%m-%d %H:%M:%S %Z'

Timestamp to date (BSD / macOS)

date -r 1710050400
date -u -r 1710050400 +'%Y-%m-%d %H:%M:%S'

# Install coreutils for GNU behaviour: brew install coreutils && gdate -d @...

Date to timestamp

date -d '2024-03-10 06:00:00 UTC' +%s        # GNU
date -j -f '%Y-%m-%d %H:%M:%S' '2024-03-10 06:00:00' +%s   # BSD

Pitfalls specific to Bash

  • date -d does not exist on macOS, and date -r means "reference file" on GNU. Scripts that work on your laptop may fail in CI, or vice versa.
  • %N (nanoseconds) is GNU-only — date +%s%3N prints a literal 3N on macOS.

Rules that apply in every language

  1. Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
  2. Name the unit in the identifier. expires_at_ms rather than expires_at costs nothing and prevents the single most common timestamp bug.
  3. Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
  4. Use 64-bit time. Anything still storing seconds in a signed 32-bit field breaks in January 2038 — see the Year 2038 problem.

The same task in other languages

Frequently asked questions

How do I get the current Unix timestamp in Bash?

Use the snippet in the "Current Unix timestamp" section above. Bash / shell works in integer seconds natively, so converting to another unit is a multiplication or an integer division away.

How do I convert a Unix timestamp to a date in Bash?

The "Timestamp to date" snippet above shows the idiomatic approach, including how to render the result in a specific time zone rather than whatever zone the machine happens to be set to.

Does Bash handle time zones and daylight saving correctly?

Yes, provided you pass an explicit zone rather than relying on the system default. The gotchas listed on this page cover the specific ways Bash / shell makes that easy to get wrong.