Unix Timestamp Code Snippets

Ready-to-use code for working with Unix timestamps in 9 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

How to use these snippets safely

Each snippet is intentionally small so it can be copied into a console, migration script, test, or API handler. Before using a value in production, check the expected unit at the boundary where the timestamp leaves your code. Many timestamp bugs happen when one service sends milliseconds and another service stores seconds without converting.

  • For browser and frontend code, expect milliseconds unless the API documentation says otherwise
  • For backend code, logs, and shell tools, Unix seconds are usually the default
  • For database filters, keep the unit consistent across all rows and indexes
  • For formatted output, prefer UTC or an explicit IANA timezone instead of the server default

Choosing a source of truth

When several services touch the same event time, pick one representation as the source of truth and convert at the edges. For example, a backend can store Unix seconds, a frontend can multiply by 1000 for Date, and a report can format the same instant as UTC or a business timezone.