JavaScript Date.now()

Complete guide to JavaScript Date.now() and the Date object for Unix timestamps. Learn creation, conversion, formatting, and common pitfalls.

Language

Date.now()

Detailed Explanation

JavaScript's Date.now() returns the current time as the number of milliseconds since the Unix epoch. It is the most direct way to get a timestamp in JavaScript and is available in all modern browsers and Node.js.

Getting timestamps:

// Current timestamp in milliseconds
Date.now()                        // 1700000000000

// Current timestamp in seconds (Unix standard)
Math.floor(Date.now() / 1000)     // 1700000000

// From a Date object
new Date().getTime()              // same as Date.now()
+new Date()                       // coercion trick, same result

Creating Date objects from timestamps:

// From milliseconds
new Date(1700000000000)           // 2023-11-14T22:13:20.000Z

// From seconds (must multiply by 1000)
new Date(1700000000 * 1000)       // same result

// WRONG: passing seconds directly
new Date(1700000000)              // 1970-01-20T16:13:20.000Z (!)

That last example is the single most common timestamp bug in JavaScript. The Date constructor always expects milliseconds. If you pass a seconds-based timestamp, you get a date in January 1970.

Formatting:

const d = new Date();
d.toISOString()       // "2024-01-15T09:30:00.000Z"
d.toUTCString()       // "Mon, 15 Jan 2024 09:30:00 GMT"
d.toLocaleDateString() // Locale-dependent

Performance timing: For measuring code execution, use performance.now() instead of Date.now(). It provides sub-millisecond precision and is not affected by system clock changes.

Time zone gotcha: JavaScript Date objects are always UTC internally. Methods like getHours() and toString() return local time based on the runtime's timezone, while getUTCHours() and toISOString() return UTC. In Node.js, you can control the timezone with the TZ environment variable. In browsers, you are stuck with the user's system timezone unless you use Intl.DateTimeFormat with an explicit timeZone option.

Use Case

In frontend applications, Date.now() is commonly used to set JWT expiration checks, debounce user input, and generate unique identifiers with timestamp prefixes.

Try It — Timestamp Converter

Open full tool