How do you convert a Unix timestamp into a readable date and time in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 6 days ago

How do you convert a Unix timestamp into a readable date and time in JavaScript?

message-square
0

In JavaScript, pass a millisecond Unix timestamp to new Date(ms) and format the resulting Date instance using Intl.DateTimeFormat (or .toLocaleString()). The most common gotcha is unit mismatch: Unix timestamps are often given in seconds, whereas JavaScript’s Date constructor expects milliseconds (seconds * 1000).


1. Converting Seconds or Milliseconds into a Date and Formatting It

Normalize seconds vs. milliseconds first (or accept an explicit unit flag), then format deterministically with Intl.DateTimeFormat and an explicit timeZone when consistency matters across servers or locales:

function formatUnixTimestamp(timestamp, { unit = "auto", locale = "en-US", timeZone = "UTC" } = {}) {
  if (typeof timestamp !== "number" || !Number.isFinite(timestamp)) {
    throw new TypeError("timestamp must be a finite number");
  }

  const ms =
    unit === "seconds" || (unit === "auto" && Math.abs(timestamp) < 1e12)
      ? timestamp * 1000
      : timestamp;

  const date = new Date(ms);
  if (Number.isNaN(date.getTime())) {
    throw new RangeError("Invalid timestamp value");
  }

  return new Intl.DateTimeFormat(locale, {
    dateStyle: "medium",
    timeStyle: "short",
    timeZone
  }).format(date);
}

console.log(formatUnixTimestamp(1735689600));              // "Jan 1, 2025, 12:00 AM" (UTC)
console.log(formatUnixTimestamp(1735689600000));           // "Jan 1, 2025, 12:00 AM" (UTC)
console.log(formatUnixTimestamp(1735689600, { timeZone: "Asia/Karachi" })); // "Jan 1, 2025, 5:00 AM"

2. ISO 8601 Strings vs. Locale-Formatted Display

Choose the output format based on whether the string is for logs/APIs or human UI display:

  • ISO 8601 UTC string (toISOString()): Best for logs, APIs, and unambiguous storage ("2025-01-01T00:00:00.000Z"):

    const isoString = new Date(1735689600 * 1000).toISOString(); console.log(isoString); // “2025-01-01T00:00:00.000Z”

  • Local vs. explicit time zone formatting: Calling .toLocaleString() without a timeZone uses the host/browser’s local time zone, which can differ between a developer’s machine, CI, and production servers—pass timeZone explicitly whenever output must be reproducible.

3. Common Traps to Avoid

  • Passing a 10-digit second timestamp directly to new Date(sec): new Date(1735689600) treats 1735689600 as 1,735,689,600 milliseconds after epoch—which is January 20, 1970, not 2025.
  • Relying on vague "auto" unit detection for far-past or far-future dates: A threshold like < 1e12 works well for recent/near-term timestamps, but explicit unit: "seconds" or unit: "milliseconds" is safer when timestamps might be near the boundary or represent historical/far-future dates.
  • Using Date.prototype.toString() for UI display: It outputs verbose local system strings and non-standard time zone names that vary across environments.

TL;DR: Multiply second-based Unix timestamps by 1000, pass milliseconds into new Date(ms), and format with Intl.DateTimeFormat (specifying locale and timeZone for consistent output) or .toISOString() for UTC ISO timestamps.

Are you formatting timestamps for end-user UI display in a specific time zone, generating UTC ISO strings for logs/APIs, or dealing with mixed second/millisecond inputs?