Record wall-clock time for an event
#Date represents an instant with millisecond precision; toISOString formats it in UTC.
Fragment
Wall time can jump when the system clock is adjusted; use a monotonic clock for elapsed duration.
Reference
Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.
TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.
TypeScript docs Node.js util ↗Node.js performance measurement ↗
Date represents an instant with millisecond precision; toISOString formats it in UTC.
Fragment
Wall time can jump when the system clock is adjusted; use a monotonic clock for elapsed duration.
performance.now measures an elapsed interval independently of ordinary wall-clock adjustments.
Fragment
Modern Node/browser API. This fragment measures synchronous work; await an asynchronous operation before taking the second reading.
Math.random supports ordinary simulation/selection; it is not a cryptographic random source.
Fragment
For security-sensitive randomness choose a documented crypto API instead.
Temporal.Duration is the standard duration type: named fields (hours, minutes, seconds and the calendar units days, weeks, months, years), ISO 8601 text such as PT8H30M, total(unit) to convert, round() to balance or round for display, and Duration.compare. Temporal.Instant.add and until do exact-time arithmetic with it; an Instant refuses days and larger units, which depend on a time zone or calendar.
Complete program
Complete program for Node 26+ or a current browser. On Node 22/24 use the milliseconds approach in the notes, or load temporal-polyfill.
In practice: parse configured durations with Duration.from, add them to an Instant for expiry times, and convert to milliseconds only at the edge, because setTimeout, Date and performance.now still take plain numbers. Use a ZonedDateTime when "one day" or "one month" has to follow a calendar.
Temporal ships enabled in Node 26 and in current Chrome and Firefox; check MDN's compatibility table for other runtimes. Node 22 and 24 run this program with temporal-polyfill 1.0.8 (node --import temporal-polyfill/global). TypeScript 6.0+ has the types in lib "esnext.temporal".
Without Temporal, durations are plain milliseconds: name the unit (const SESSION_TTL_MS = 8 * 3_600_000 + 30 * 60_000) and add to an instant with new Date(issued.getTime() + SESSION_TTL_MS).
setTimeout clamps delays above 2^31 - 1 ms (about 24.8 days) to 1 ms and Node prints a TimeoutOverflowWarning; schedule long waits in steps.
toLocaleString formats with Intl.DurationFormat ("8 hr, 30 min" in English) and falls back to the ISO string (PT8H30M) where Intl.DurationFormat is missing, as on Node 22; the exact text depends on the ICU version, so do not compare it in tests.
Temporal.Instant is the standard type for an exact time. Instant.from parses ISO 8601 / RFC 9557 strings and requires a Z or an offset (it accepts more than RFC 3339, such as a missing seconds field or the basic format, so check the shape with a regular expression first when you need strict RFC 3339). It applies the offset and throws a RangeError for an impossible date or a non-ISO string. toString() formats as UTC with only the fraction digits needed (fractionalSecondDigits fixes them, timeZone shows another offset), JSON.stringify uses it, and epochMilliseconds is Unix time in milliseconds.
Complete program
Complete program for Node 26+ or a current browser. On Node 22/24 use the Date approach in the notes, or load temporal-polyfill.
In practice: send and store full RFC 3339 timestamps with an offset, parse them with Instant.from, and use toLocaleString (Intl) only for text meant for people. Convert to and from Date through epoch milliseconds where older APIs need one.
Temporal ships enabled in Node 26 and in current Chrome and Firefox. Node 22 and 24 run this program with temporal-polyfill 1.0.8 (node --import temporal-polyfill/global); TypeScript 6.0+ types it with lib "esnext.temporal".
Without Temporal: Date.parse reads a date-time without an offset as local time, returns NaN for invalid input, and in V8 rolls 2026-02-30 over to 2 March. Check the shape with a regex such as /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/ and check that new Date(Date.UTC(year, month - 1, day)).getUTCDate() gives the same day back before trusting it.
Date.prototype.toISOString always prints milliseconds (.000Z) and throws a RangeError on an Invalid Date.
Temporal.ZonedDateTime is the standard type for a time in an IANA zone: an exact instant plus the zone, with its daylight-saving rules. instant.toZonedDateTimeISO("America/New_York") views an instant there, ZonedDateTime.from("2026-03-09T09:00[America/New_York]") builds a wall time in the zone, and .offset shows the offset that applies. add({ days: 1 }) is calendar arithmetic that keeps the wall-clock time across a DST change, while add({ hours: 24 }) is exact time. A wall time in a DST gap is moved forward by default; disambiguation: "reject" throws instead. Unknown zones throw a RangeError.
Complete program
Complete program for Node 26+ or a current browser; its assertions hold in any local zone. On Node 22/24 use the Intl approach in the notes, or load temporal-polyfill.
In practice: store instants in UTC and the user's IANA zone name (not an offset) alongside, do "same time tomorrow" arithmetic on a ZonedDateTime, and format for people with toLocaleString.
Temporal ships enabled in Node 26 and in current Chrome and Firefox. Node 22 and 24 run this program with temporal-polyfill 1.0.8 (node --import temporal-polyfill/global); TypeScript 6.0+ types it with lib "esnext.temporal".
Without Temporal, a Date has only UTC and the local zone. new Intl.DateTimeFormat("en-GB", { timeZone: "America/New_York", timeZoneName: "longOffset" }).format(date) shows an instant in another zone, but building a wall time in that zone needs a library such as date-fns-tz or Luxon.
Display text (toLocaleString, Intl) comes from ICU and CLDR and changes between releases: Node 24 writes the UTC long offset as "GMT+00:00" where Node 22 wrote "GMT". Assert on offset and fields, not on formatted strings.
Node bundles its own time zone database, so zone rules update with Node releases, not with the OS. The local zone comes from TZ or the OS; servers usually run in UTC.
Math.random cannot be seeded, so its output cannot be replayed. For tests, simulations and procedural content, use a small seeded PRNG such as mulberry32 (32-bit state, a few lines, good statistical quality for this use) and derive everything from it: integers in a range, shuffles (Fisher-Yates), choices.
Complete program
Complete program. Set TEST_SEED to replay a different sequence.
In practice: read the seed from an environment variable or test parameter, print it when a test fails, and pass the generator into the code under test instead of calling Math.random inside it. Property-testing libraries such as fast-check do this for you and report the failing seed.
mulberry32 has a period of 2^32; for long simulations use a larger-state generator such as xoshiro128** or sfc32.
Math.floor(next() * n) has a tiny bias for large n; it is negligible for tests but not for anything that decides money or fairness.
Seeded generators are predictable by design: never use them for tokens or passwords.
Use the operating system's cryptographically secure generator, never Math.random. crypto.getRandomValues fills a typed array (Web Crypto, global in Node and browsers), crypto.randomUUID returns a version 4 UUID with 122 random bits, and node:crypto adds randomBytes and randomInt (an unbiased integer in a range).
Complete program
Complete program.
In practice: make tokens from at least 16 bytes, preferably 32, encoded with base64url or hex; store only a hash of long-lived tokens; and compare presented secrets with timingSafeEqual so the comparison time does not leak where they differ.
getRandomValues accepts at most 65,536 bytes per call and only integer typed arrays.
randomUUID in browsers requires a secure context (HTTPS or localhost).
timingSafeEqual throws if the buffers differ in length; hash both sides first (for example SHA-256) when lengths can differ.