How to Get Epoch Timestamps in JavaScript

Complete guide to working with epoch timestamps in JavaScript and Node.js. Get current time, convert dates, handle milliseconds vs seconds, and format output.

Programming

Detailed Explanation

Epoch Timestamps in JavaScript

JavaScript's Date object uses milliseconds since the Unix epoch internally. This is important to remember because most other systems (databases, APIs, Unix tools) use seconds.

Getting the Current Epoch

// Milliseconds (13 digits)
Date.now();              // 1705312200000
new Date().getTime();    // 1705312200000

// Seconds (10 digits)
Math.floor(Date.now() / 1000);  // 1705312200

Converting Epoch to Date

// From seconds
const date = new Date(1705312200 * 1000);
console.log(date.toISOString());  // "2024-01-15T09:30:00.000Z"
console.log(date.toLocaleString()); // Localized format

// From milliseconds
const date2 = new Date(1705312200000);

Converting Date to Epoch

// From ISO string
const epoch = Math.floor(
  new Date("2024-01-15T09:30:00Z").getTime() / 1000
);

// From date components
const epoch2 = Math.floor(
  new Date(2024, 0, 15, 9, 30, 0).getTime() / 1000
);
// Note: months are 0-indexed in JavaScript!

Common Patterns

Countdown calculation:

const target = new Date("2025-01-01T00:00:00Z").getTime();
const now = Date.now();
const remainingMs = target - now;
const remainingSeconds = Math.floor(remainingMs / 1000);
const days = Math.floor(remainingSeconds / 86400);
const hours = Math.floor((remainingSeconds % 86400) / 3600);

Safe epoch detection:

function normalizeToMs(timestamp) {
  return timestamp < 10000000000 ? timestamp * 1000 : timestamp;
}

Timezone Gotchas

Date.now() always returns UTC-based milliseconds regardless of the user's timezone. However, new Date(year, month, day) creates a date in the local timezone. Always use ISO strings or UTC methods when precision matters.

Use Case

Reference this guide when building countdown timers, scheduling features, or any JavaScript application that needs to work with Unix timestamps. It covers the most common patterns and pitfalls specific to JavaScript's millisecond-based Date API.

Try It — Epoch Countdown

Open full tool