JavaScript Date and Time

Create, format, and modify dates in JavaScript with timestamps, UTC, and common calculations.

TL;DR

  1. Create dates using new Date with several input options.
  2. Read date parts with getFullYear(), change them with setFullYear().
  3. Format dates with toISOString() for machines and toLocaleDateString() for humans.

Creating Dates

    new Date()

    Accepts four different argument shapes for creating dates.

    const now = new Date();
    From a string or parts

    Parse a date string, or pass year/month/day/time parts.

    const d = new Date("2025-10-11");
    const custom = new Date(2025, 9, 11, 15, 30);
    From milliseconds

    Pass a millisecond timestamp to build a date from a number.

    const fromMs = new Date(1697040000000);

Reading and Changing Parts

    getFullYear() / setFullYear()

    Reads the four-digit year, or sets it to change the date.

    now.getFullYear(); // 2025
    date.setFullYear(2026);
    getMonth() / setMonth()

    Reads or sets the month as a zero-indexed number (0 = Jan).

    now.getMonth(); // 9 means October
    date.setMonth(0); // January
    getDate() / getDay() / setDate()

    Day of month or weekday; setDate() changes it in place.

    now.getDate(); now.getDay(); // 0 = Sunday
    date.setDate(1);

Timestamps and UTC

    Date.now()

    Returns the current timestamp in milliseconds since the epoch.

    const ts = Date.now();
    getUTC methods

    Reads times in universal coordinated time, not local timezone.

    now.getUTCFullYear(); now.getUTCHours();
    Time components

    Read hours, minutes, seconds; setHours() sets all three.

    now.getHours();
    date.setHours(12, 0, 0);
    Easy comparisons

    Timestamps make it easy to compare or subtract two dates.

    date1.getTime() < date2.getTime();

Formatting and Math

    toISOString() / toLocaleDateString()

    Formats a date for machines (UTC) or a readable local string.

    now.toISOString();
    now.toLocaleDateString();
    Adding days

    Read the current date and add to it to shift by any amount.

    const today = new Date();
    today.setDate(today.getDate() + 5);
    Subtracting dates

    Subtract two dates to get the difference in milliseconds.

    const diffMs = date1 - date2; // milliseconds

Tips

  1. For complex date math like time zones, recurring events, or relative time, use a library like date-fns or Luxon.
  2. Store dates as ISO strings or timestamps in APIs and databases, converting to a Date object only for display.

Warnings

  1. JavaScript months are zero-indexed, so passing 0 means January and passing 11 means December, not month 12.
  2. Date string parsing varies by browser for non-ISO formats, so prefer ISO 8601 or new Date(year, month, day) instead.

In Practice

FAQ