Timestamp2Date
← Back to blogs
•Unix TimestampJavaScriptDate

Unix Timestamp JavaScript Examples

Unix timestamp is the number of elapsed time units since 1970-01-01T00:00:00Z (Unix epoch).

In JavaScript, one rule is essential:

  • Date stores time in milliseconds
  • many APIs use Unix time in seconds

JavaScript Unix Timestamp Cheatsheet

Get current timestamp

const nowMs = Date.now();
const nowSec = Math.floor(Date.now() / 1000);

Convert timestamp to Date

const fromSeconds = new Date(1772400000 * 1000);
const fromMilliseconds = new Date(1772400000000);

Convert Date to timestamp

const d = new Date("2026-03-02T12:00:00Z");
const unixMs = d.getTime();
const unixSec = Math.floor(d.getTime() / 1000);

Parse UTC vs local time

// UTC instant
const utcSec = Math.floor(new Date("2026-03-02T12:00:00Z").getTime() / 1000);

// Local clock time (year, monthIndex, day, hour, min, sec)
const localSec = Math.floor(new Date(2026, 2, 2, 12, 0, 0).getTime() / 1000); // monthIndex is 0-based, so 2 = March

Format timestamp for display

const tsSec = 1772400000;
const date = new Date(tsSec * 1000);

const localText = new Intl.DateTimeFormat("en-US", {
  dateStyle: "medium",
  timeStyle: "medium",
}).format(date);

const utcText = new Intl.DateTimeFormat("en-US", {
  dateStyle: "medium",
  timeStyle: "medium",
  timeZone: "UTC",
}).format(date);

Compare expiry safely

function isExpired(expiresAtSec) {
  return Math.floor(Date.now() / 1000) >= expiresAtSec;
}

Use Math.floor for Unix seconds comparisons. Avoid Math.round, which can shift boundary behavior near second transitions.

Normalize unknown unit input (sec/ms)

function toMilliseconds(ts) {
  if (!Number.isFinite(ts)) throw new TypeError("Invalid timestamp");

  const abs = Math.abs(ts);
  if (abs >= 1e9 && abs < 1e10) return ts * 1000; // seconds
  if (abs >= 1e12 && abs < 1e13) return ts; // milliseconds

  throw new RangeError("Unsupported or ambiguous timestamp unit");
}

Nanoseconds input (BigInt)

function nanosecondsToDate(nsInput) {
  const ns = BigInt(nsInput);
  const ms = Number(ns / 1_000_000n); // truncate sub-ms part
  return new Date(ms);
}

Digit-length quick guide

  • 10 digits: usually seconds
  • 13 digits: usually milliseconds
  • 16 digits: usually microseconds
  • 19 digits: usually nanoseconds

Common mistakes

  1. Sending Date.now() directly to an API that expects seconds.
  2. Comparing milliseconds with seconds in auth/expiry logic.
  3. Parsing time strings without timezone and assuming UTC.
  4. Mixing seconds and milliseconds in one DB field.

Practical naming convention

Use unit-explicit names:

  • created_at_sec
  • updated_at_ms
  • expires_at_sec

Useful tools