Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 156 ยท Built-in Tools

Dates and Times

Create and read JavaScript Date objects, work with timestamps, add days safely, avoid time zone traps, and see what the new Temporal API changes.

Almost every app deals with time: a post was published, an order ships on Friday, a trial ends in 14 days. JavaScript has handled this with the built-in Date object since 1995. It works, and you will meet it in every codebase, but it has some famous quirks โ€” months that start at zero, objects you can change by accident, and surprising time zone behavior.

In this lesson you will learn how a Date really works under the hood, how to create, read and change one, how to do simple date math, and which traps to avoid. At the end you will meet Temporal, the modern replacement that is arriving in browsers now.

A Date is just a timestamp

Inside, a Date holds a single number: the count of milliseconds since midnight UTC on January 1, 1970 (the "Unix epoch"). Everything else โ€” the year, the weekday, the hour โ€” is calculated from that number when you ask for it.

JavaScript
const now = new Date();     // the current moment
console.log(now.getTime()); // e.g. 1792058400000
console.log(Date.now());    // the same kind of number, without creating an object

Because the number is in UTC, the same Date describes the same instant everywhere on Earth. What changes from place to place is how that instant is displayed โ€” 9:00 in London is 10:00 in Paris.

Creating dates

There are four common ways to make a Date:

JavaScript
new Date();                          // now
new Date(1792058400000);             // from a timestamp in milliseconds
new Date(2026, 2, 15, 9, 30);        // from parts, in YOUR local time zone
new Date("2026-03-15T09:30:00Z");    // from an ISO 8601 string

The parts version has the most famous quirk in JavaScript: months are numbered from 0. January is 0, March is 2, December is 11. Days of the month start at 1 as usual.

JS Creating and reading dates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The getters you will use most:

Getter Returns
getFullYear() four-digit year
getMonth() 0โ€“11
getDate() day of the month, 1โ€“31
getDay() day of the week, 0 (Sunday) โ€“ 6
getHours(), getMinutes(), getSeconds(), getMilliseconds() time parts
getTime() the timestamp in milliseconds

Note the confusing pair: getDate() is the day of the month, getDay() is the weekday. Avoid getYear(), an old method that returns the year minus 1900.

Parsing strings

Only one string format is guaranteed to parse the same way in every browser: ISO 8601, such as "2026-03-15" or "2026-03-15T09:30:00". Other formats like "03/15/2026" or "15 March 2026" may work in one browser and fail in another. When you parse user input, split it yourself or use an <input type="date">, whose value is always ISO.

There is one more trap here, and it catches everyone:

  • A date-only ISO string ("2026-03-15") is treated as UTC midnight.
  • A date-time string without a zone ("2026-03-15T00:00") is treated as local time.

So new Date("2026-03-15") shows as March 14 for anyone west of Greenwich, such as users in the Americas. If you want a calendar date in local time, pass parts (new Date(2026, 2, 15)) or add a time ("2026-03-15T00:00").

Invalid dates

A bad input does not throw. You get an "Invalid Date" whose timestamp is NaN:

JavaScript
const bad = new Date("next Tuesday");
console.log(bad.getTime());              // NaN
console.log(Number.isNaN(bad.getTime())); // true โ€” the reliable check

Changing a date

Every getter has a matching setter: setFullYear(), setMonth(), setDate(), setHours() and so on. Setters change the object in place โ€” a Date is mutable, unlike strings and numbers.

Setters also roll over values that are out of range. Setting day 32 of January gives February 1. That sounds like a bug, but it is the easiest way to add days:

JS Adding days and copying dates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Months roll over too, and that leads to a classic surprise. Adding one month to January 31 asks for "February 31", which rolls into March:

JavaScript
const d = new Date(2026, 0, 31);   // Jan 31
d.setMonth(d.getMonth() + 1);
console.log(d.toDateString());     // Tue Mar 03 2026

If you need "end of next month" behavior, clamp the day yourself, or use Temporal (below), which clamps automatically.

Date math with timestamps

Since a Date is a number underneath, subtracting two dates gives the difference in milliseconds. (The - operator converts both dates to their timestamps.)

JS Days until an event

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two details matter:

  • Use Math.round() when converting to days. In many countries one day a year has 23 hours and another has 25 (daylight saving time), so an exact division can give 71.958 instead of 72.
  • Never compare dates with ===. Two Date objects are different objects even when they hold the same moment; compare getTime() values instead (see Comparison and Equality). The < and > operators do work, because they compare timestamps.

Time zones: local vs UTC

Every getter and setter has a UTC twin: getUTCHours(), setUTCDate(), and so on. The plain versions use the time zone of the computer running the code; the UTC versions ignore it.

JavaScript
const meeting = new Date("2026-06-01T15:00:00Z"); // 15:00 UTC
meeting.getUTCHours();   // 15, everywhere
meeting.getHours();      // 16 in London (summer time), 11 in New York, 0 in Tokyo next day

You can ask for the user's time zone and its current offset:

JavaScript
Intl.DateTimeFormat().resolvedOptions().timeZone; // e.g. "Europe/Berlin"
new Date().getTimezoneOffset();                   // minutes BEHIND UTC, e.g. -120

The sign of getTimezoneOffset() is backward from what most people expect: it is positive west of UTC and negative east of it.

A rule that avoids most time zone bugs: store and send moments as UTC (a timestamp or an ISO string ending in Z, from toISOString()), and convert to local time only when you display them. A Date cannot represent "9:00 in Tokyo" on a computer set to Berlin โ€” for that you need Intl or Temporal.

Formatting dates

Date has a handful of built-in string methods:

JavaScript
const d = new Date(2026, 2, 15, 9, 30);
d.toISOString();        // "2026-03-15T08:30:00.000Z" (in UTC; depends on your zone)
d.toDateString();       // "Sun Mar 15 2026"
d.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" });
                        // "Sunday, March 15"
d.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }); // "09:30"

The toLocaleโ€ฆ methods accept a locale and options, and are really a shortcut for Intl.DateTimeFormat. The next lesson, Formatting with Intl, covers them properly โ€” including formatting in another time zone. For quick padding, you can also build strings yourself with padStart(): String(d.getMonth() + 1).padStart(2, "0").

Date recipes

These small helpers come up again and again. Each one avoids a classic trap, and every example below prints the same result on any computer, whatever its time zone.

Days between two dates

Subtracting two dates gives milliseconds, but a "day" is not always 24 hours: when clocks change for daylight saving time, a local day can be 23 or 25 hours long. The safe way is to convert both dates to UTC midnight first, then divide.

JS Days between dates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Date.UTC() takes the same arguments as new Date(y, m, d) (months still start at 0) but returns a timestamp in UTC. Because it ignores local time, no daylight saving shift can sneak in.

Adding days and finding month boundaries

setDate() rolls over automatically, which is exactly what you want for "30 days from now". A day number of 0 means "the day before the 1st", so the last day of a month is day 0 of the next month.

JS Month boundaries and weekends

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Adding months is not the same as adding 30 days. new Date(2026, 0, 31).setMonth(1) asks for "February 31", which rolls over to March 3. If you need "the same day next month, but never later than the month's last day", clamp the day with Math.min(day, daysInMonth(year, month)).

Clock strings: hh:mm:ss and 12-hour time

Build a clock string yourself with padStart(), or use the toLocale... methods for a ready-made one. For a 12-hour clock, use the remainder after dividing by 12, and treat the result 0 as 12.

JS Formatting clock time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

UTC getters, setters and other time zones

Use the UTC twins when the answer must not depend on where the code runs, such as building a calendar of dates stored as UTC or computing a deadline "at midnight UTC". To show one instant in another zone, ask Intl.DateTimeFormat for it with the timeZone option; this does not change the date, only its display.

JS One instant, three zones

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Validating dates

An invalid Date is still a Date object, so instanceof is not enough: check that its timestamp is not NaN. Also remember that new Date(2026, 1, 31) does not fail, it rolls over to March 3. To validate user input such as "2026-02-31", build the date and check that it reads back the same.

JS Strict date validation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For locale-specific formats and relative phrases such as "3 days ago", see Formatting with Intl.

Temporal: the modern date API

Because Date is so hard to use correctly, a new built-in called Temporal was designed to replace it. It fixes the major problems:

  • Objects are immutable โ€” methods return new values instead of changing the old one.
  • Months are numbered 1โ€“12.
  • Separate types say exactly what you mean: Temporal.PlainDate (a calendar date, no time or zone), Temporal.PlainTime, Temporal.ZonedDateTime (a moment in a named time zone), Temporal.Instant (an exact moment) and Temporal.Duration.
  • Date math respects calendars and daylight saving time.

Browser support: Temporal is new. Firefox shipped it in 2025 and Chromium-based browsers (Chrome, Edge) followed in early 2026; Safari support was still in progress at the time of writing, and older browsers don't have it at all. Always feature-detect with typeof Temporal !== "undefined", or use the official polyfill in production. The example below checks first, so it is safe to run anywhere.

JS Temporal with feature detection

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Until Temporal works everywhere your users are, Date (plus Intl for display) remains the safe default โ€” and knowing its quirks is what keeps your code correct.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What date does new Date(2026, 1, 10) create?

    Months are zero-based in Date: 0 is January, so 1 is February.
  2. 2. Which is the reliable way to check whether two Date objects hold the same moment?

    Two different Date objects are never === each other. Compare their numeric timestamps instead.
  3. 3. A user in New York runs new Date("2026-03-15").getDate(). What do they get?

    Date-only ISO strings are parsed as UTC. Midnight UTC is still March 14 in New York, so the local day is 14.
  4. 4. What does getDay() return?

    getDay() is the weekday. For the day of the month use getDate().
  5. 5. Why is Temporal's PlainDate.add() safer than Date.setDate()?

    Temporal objects are immutable, so you can't accidentally change a date that other code is also using.

Summary

  • A Date stores one number: milliseconds since January 1, 1970 UTC. Getters calculate local parts from it.
  • Months are 0โ€“11 in Date; getDate() is the day of the month, getDay() the weekday.
  • Only ISO 8601 strings parse reliably; date-only strings are read as UTC, date-time strings as local.
  • Setters mutate the date and roll over out-of-range values. Copy with new Date(d) before changing.
  • Subtract dates to get milliseconds, round when converting to days, and compare with getTime().
  • Store UTC, display local. Temporal is the immutable, clearer future โ€” feature-detect it before use.

Next: The Temporal API.