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 -ddoes not exist on macOS, anddate -rmeans "reference file" on GNU. Scripts that work on your laptop may fail in CI, or vice versa.%N(nanoseconds) is GNU-only —date +%s%3Nprints a literal3Non macOS.
Rules that apply in every language
- Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
- Name the unit in the identifier.
expires_at_msrather thanexpires_atcosts nothing and prevents the single most common timestamp bug. - Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
- 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
- Python float seconds
- JavaScript integer milliseconds
- PHP integer seconds
- Java integer milliseconds
- Go integer seconds and nanoseconds
- TypeScript integer milliseconds
- Ruby float seconds
- C# ticks (100 ns)
- Rust seconds + nanoseconds
- SQL varies by engine
- C++ chrono duration
- Swift float seconds
- Kotlin integer milliseconds
- C time_t seconds
- Perl integer seconds
- Dart integer milliseconds
- PowerShell .NET DateTimeOffset
- Scala integer milliseconds
- R float seconds
- Excel days since 1899-12-30
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.