Tool

Unix Timestamp Code Snippets

Ready-to-use code for working with Unix timestamps in 8 programming languages and databases. Covers getting the current timestamp, converting to a date, and formatting output.

About these code examples

All examples use the value 1700000000 as a sample Unix timestamp in seconds, which corresponds to November 15, 2023 06:13:20 UTC. Replace this with your own timestamp. Examples that show milliseconds use 1700000000000 (the same moment × 1000).

Seconds vs milliseconds by language

The most common mistake is mixing up seconds and milliseconds. Use this quick reference:

  • Milliseconds (× 1000): JavaScript Date.now(), Java System.currentTimeMillis(), C# DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
  • Seconds (÷ 1000 to compare with JS): Python time.time(), PHP time(), Go time.Now().Unix(), Ruby Time.now.to_i, Rust SystemTime::now().as_secs()
  • SQL: MySQL UNIX_TIMESTAMP() → seconds; PostgreSQL EXTRACT(EPOCH) → seconds with fractional part

Frequently asked questions

Why does JavaScript use milliseconds while most languages use seconds?
JavaScript was designed for the browser where millisecond precision is useful for animations and event timing. Most server-side languages default to seconds. Always confirm the unit when integrating with an external API.
How do I get the Unix timestamp in JavaScript without a library?
Use Math.floor(Date.now() / 1000) for seconds or Date.now() for milliseconds. Both are built-in to every JavaScript runtime.
How do I convert a Unix timestamp to a date in Python?
Use datetime.datetime.fromtimestamp(ts) for local time or datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc) for UTC. Both are in the standard library's datetime module.