JavaScript Dates, Times and Intl: Date, Time Zones and Temporal

Dates are one of the most bug-prone areas of any application, and so one of the most rewarding for testers: wrong time zones, off-by-one days, months that start at zero, 31 January plus one month, and formats that differ between India and the US. In this lesson you will learn how JavaScript stores dates, how to create and parse them safely, how time zones and UTC work, how to add and compare dates, how to format dates, numbers and currencies for any locale with Intl, and how the new Temporal API fixes the old Date object’s problems. The examples ran on a computer set to India Standard Time; where an output depends on the computer’s time zone, it is labelled.

Advertisement

📖 What You’ll Learn: how Date stores time as milliseconds since 1970 UTC, creating dates, zero-based months, parsing ISO strings (and the date-only UTC trap), getters and setters, UTC vs local time, toISOString, adding days and months, differences between dates, comparing dates, Intl.DateTimeFormat with locales and time zones, Intl.NumberFormat for INR and other currencies, Intl.RelativeTimeFormat, Temporal (PlainDate, ZonedDateTime, Duration), and generating date test data.


🕰️ How JavaScript Stores Dates

Definition: a Date object holds a single number: the milliseconds since 1 January 1970 00:00:00 UTC (the Unix epoch). Everything else, the day, the hour, the time zone, is calculated from that number when you ask for it.

📄 epoch.js

const epoch = new Date(0);
const launch = new Date("2026-11-23T10:30:00Z");      // Z = UTC

console.log(epoch.toISOString());
console.log(launch.getTime());                       // milliseconds since 1970
console.log(launch.toISOString());                   // always UTC
console.log(launch.toString());                      // local time of this computer
console.log(typeof Date.now(), Date.now() > launch.getTime() - 10 ** 12);

⌨️ Terminal

node epoch.js

🖥️ Output (computer time zone: India Standard Time, UTC+05:30)

1970-01-01T00:00:00.000Z
1795429800000
2026-11-23T10:30:00.000Z
Mon Nov 23 2026 16:00:00 GMT+0530 (India Standard Time)
number true
Create withMeaning
new Date()Now
new Date(ms)Milliseconds since the epoch
new Date("2026-11-23T10:30:00Z")ISO string in UTC (safest)
new Date("2026-11-23T10:30:00+05:30")ISO string with an explicit offset
new Date(2026, 10, 23, 10, 30)Parts in local time; month is 0-based (10 = November)
Date.UTC(2026, 10, 23)Parts in UTC, returns milliseconds

⚠️ The Classic Date Traps

📄 traps.js

// 1. Months start at 0
console.log(new Date(2026, 0, 15).toDateString());     // January, not "month 0"
console.log(new Date(2026, 12, 1).toDateString());     // month 12 rolls over to next January

// 2. A date-only ISO string is UTC; a date-time string without Z is LOCAL
console.log(new Date("2026-11-23").toISOString());
console.log(new Date("2026-11-23T00:00").toISOString());

// 3. Invalid dates do not throw
const bad = new Date("31/12/2026");
console.log(bad.getTime(), String(bad), Number.isNaN(bad.getTime()));

// 4. Overflow is silently "fixed"
console.log(new Date(2026, 1, 30).toDateString());      // 30 February -> 2 March

// 5. Dates are objects: == and === compare references
const a = new Date("2026-11-23T00:00:00Z"), b = new Date("2026-11-23T00:00:00Z");
console.log(a === b, a.getTime() === b.getTime());

⌨️ Terminal

node traps.js

🖥️ Output (computer time zone: India Standard Time, UTC+05:30)

Thu Jan 15 2026
Fri Jan 01 2027
2026-11-23T00:00:00.000Z
2026-11-22T18:30:00.000Z
NaN Invalid Date true
Mon Mar 02 2026
false true

⚠️ Watch out: In India, new Date("2026-11-23T00:00") is 18:30 on 22 November in UTC, so a test that formats it in UTC shows the previous day. Off-by-one-day bugs almost always come from mixing local time and UTC. Store and send dates as ISO strings in UTC, and convert to local time only for display.

💡 Tip: Always validate parsed dates with Number.isNaN(date.getTime()). The format "31/12/2026" is not understood by Date; split it yourself or use a library or Temporal.


Advertisement

🔢 Reading and Changing Parts

Getters such as getFullYear() return local values; getUTCFullYear() and friends return UTC values. Setters change the date in place and handle overflow, which makes date arithmetic easy:

📄 parts.js

const d = new Date("2026-11-23T20:00:00Z");
console.log("local:", d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), "day", d.getDay());
console.log("UTC:  ", d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), d.getUTCHours(), "day", d.getUTCDay());

// add days: copy first, then setDate handles month and year rollover
function addDays(date, days) {
  const copy = new Date(date);
  copy.setDate(copy.getDate() + days);
  return copy;
}
console.log(addDays(new Date(2026, 11, 30), 5).toDateString());

// difference in whole days (use UTC midnights to avoid daylight-saving surprises)
const daysBetween = (a, b) => Math.round((Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()) - Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) / 86_400_000);
console.log(daysBetween(new Date(2026, 0, 1), new Date(2026, 11, 31)));

// compare with < and > (they compare getTime())
const deadline = new Date("2026-12-01T00:00:00Z");
console.log(d < deadline, [deadline, d].sort((x, y) => x - y).map((x) => x.toISOString().slice(0, 10)));

⌨️ Terminal

node parts.js

🖥️ Output (computer time zone: India Standard Time, UTC+05:30)

local: 2026 11 24 1 day 2
UTC:   2026 11 23 20 day 1
Mon Jan 04 2027
364
true [ '2026-11-23', '2026-12-01' ]

⚠️ Watch out: Adding months with setMonth overflows: 31 January + 1 month becomes 3 March (2 March in a leap year), not 28/29 February. Decide what your product should do and test it explicitly. Temporal, below, clamps to the end of the month.


🌍 Formatting with Intl.DateTimeFormat

Intl.DateTimeFormat (and the shortcut toLocaleDateString) formats a date for any locale and time zone, with no library. Passing timeZone makes the output the same on every computer:

📄 format.js

const meeting = new Date("2026-11-23T09:30:00Z");

const fmt = (locale, options) => new Intl.DateTimeFormat(locale, options).format(meeting);

console.log(fmt("en-IN", { dateStyle: "full", timeStyle: "short", timeZone: "Asia/Kolkata" }));
console.log(fmt("en-US", { dateStyle: "full", timeStyle: "short", timeZone: "America/New_York" }));
console.log(fmt("en-GB", { dateStyle: "medium", timeStyle: "long", timeZone: "Europe/London" }));
console.log(fmt("hi-IN", { dateStyle: "long", timeZone: "Asia/Kolkata" }));
console.log(fmt("en-IN", { day: "2-digit", month: "short", year: "numeric", timeZone: "Asia/Kolkata" }));
console.log(fmt("en-US", { weekday: "short", hour: "numeric", minute: "2-digit", hour12: true, timeZone: "Asia/Tokyo" }));

// build a custom format such as 23-11-2026 from parts
const parts = Object.fromEntries(
  new Intl.DateTimeFormat("en-IN", { day: "2-digit", month: "2-digit", year: "numeric", timeZone: "Asia/Kolkata" })
    .formatToParts(meeting).map((p) => [p.type, p.value])
);
console.log(`${parts.day}-${parts.month}-${parts.year}`);

⌨️ Terminal

node format.js

🖥️ Output

Monday, 23 November 2026 at 3:00 pm
Monday, November 23, 2026 at 4:30 AM
23 Nov 2026, 09:30:00 GMT
23 नवंबर 2026
23 Nov 2026
Mon 6:30 PM
23-11-2026

💡 Tip: Testing a date shown in the UI? Format the expected value with the same locale and time zone the app uses, instead of hard-coding a string. Playwright can also fix the browser’s locale and time zone (locale: "en-IN", timezoneId: "Asia/Kolkata" in the config), which makes date tests independent of the CI machine.


💰 Numbers, Currency, Relative Time and Lists

The rest of Intl formats numbers, money, “3 days ago” and lists, all locale-aware. Note the Indian lakh/crore grouping in en-IN:

📄 intl.js

const amount = 1234567.891;
console.log(new Intl.NumberFormat("en-IN").format(amount));
console.log(new Intl.NumberFormat("en-US").format(amount));
console.log(new Intl.NumberFormat("de-DE").format(amount));

console.log(new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(2497));
console.log(new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(29.9));
console.log(new Intl.NumberFormat("en-IN", { style: "percent", maximumFractionDigits: 1 }).format(0.8765));
console.log(new Intl.NumberFormat("en-IN", { notation: "compact" }).format(1_500_000));

const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
console.log(rtf.format(-1, "day"), "|", rtf.format(3, "hour"), "|", rtf.format(-2, "week"));

console.log(new Intl.ListFormat("en", { type: "conjunction" }).format(["Chromium", "Firefox", "WebKit"]));
console.log(new Intl.PluralRules("en").select(1), new Intl.PluralRules("en").select(5));

⌨️ Terminal

node intl.js

🖥️ Output

12,34,567.891
1,234,567.891
1.234.567,891
₹2,497.00
$29.90
87.7%
15L
yesterday | in 3 hours | 2 weeks ago
Chromium, Firefox, and WebKit
one other

⚠️ Watch out: Some formats contain special spaces (for example a narrow no-break space before “PM” in en-US times). A test that compares with a typed string containing a normal space fails although both look identical. Normalise with .replace(/\s/g, " ") or build the expected value with Intl too.


Advertisement

⏳ Temporal: The Modern Date API

Temporal is the new built-in date and time API that fixes Date’s problems: objects are immutable, months start at 1, and there are separate types for “a date with no time”, “a time in a zone” and “a duration”. It ships in Node.js 26 and recent browsers:

📄 temporal.js

const due = Temporal.PlainDate.from("2026-01-31");           // a calendar date, no time zone
console.log(due.add({ months: 1 }).toString());              // clamps: 2026-02-28
console.log(due.add({ days: 30 }).toString(), due.month, due.dayOfWeek);

const start = Temporal.PlainDate.from("2026-11-23");
const end = Temporal.PlainDate.from("2027-01-15");
console.log(start.until(end).toString(), start.until(end, { largestUnit: "months" }).toString());
console.log(Temporal.PlainDate.compare(start, end));

const release = Temporal.ZonedDateTime.from("2026-11-23T18:00[Asia/Kolkata]");
console.log(release.withTimeZone("America/New_York").toString());
console.log(release.toInstant().toString());                  // the same moment in UTC

const sprint = Temporal.Duration.from({ weeks: 2, days: 3 });
console.log(sprint.total({ unit: "days", relativeTo: start }), start.add(sprint).toString());   // weeks need a start date

⌨️ Terminal

node temporal.js

🖥️ Output

2026-02-28
2026-03-02 1 6
P53D P1M23D
-1
2026-11-23T07:30:00-05:00[America/New_York]
2026-11-23T12:30:00Z
17 2026-12-10

Durations with weeks, months or years need a relativeTo date before they can be converted to days, because a month is not a fixed number of days. Temporal makes you say which month you mean instead of guessing.

Temporal typeRepresentsExample use
PlainDateA calendar dateBirthdays, due dates
PlainTime / PlainDateTimeA wall-clock time, no zoneOpening hours
ZonedDateTimeA date-time in a specific time zoneMeetings, flights
InstantAn exact moment (like Date)Timestamps, logs
DurationAn amount of timeSprint length, timeouts

📌 Note: Libraries such as date-fns, Day.js and Luxon remain common in existing projects and in browsers that do not support Temporal yet.


🧪 Tester Scenario: Generating Date Test Data

Date rules (“must be 18 or older”, “booking at least 1 day ahead”, “expires after 30 days”) need boundary dates relative to today. Generate them instead of hard-coding them, or the tests start failing on their own a year later:

📄 date-data.js

const iso = (d) => d.toString();

function dateTestData(today) {
  return {
    exactly18: iso(today.subtract({ years: 18 })),                    // valid: 18 today
    oneDayShort: iso(today.subtract({ years: 18 }).add({ days: 1 })),  // invalid: 18 tomorrow
    tomorrow: iso(today.add({ days: 1 })),
    yesterday: iso(today.subtract({ days: 1 })),
    endOfMonth: iso(today.with({ day: today.daysInMonth })),
    leapDay: iso(Temporal.PlainDate.from("2028-02-29")),
    in30Days: iso(today.add({ days: 30 })),
  };
}

const isAdult = (birth, today) => Temporal.PlainDate.compare(Temporal.PlainDate.from(birth).add({ years: 18 }), today) <= 0;

// use a FIXED "today" in tests so results never change; in the app it would be Temporal.Now.plainDateISO()
const today = Temporal.PlainDate.from("2026-11-23");
const data = dateTestData(today);
console.log(data);
console.log("exactly 18 is adult:", isAdult(data.exactly18, today));
console.log("one day short is adult:", isAdult(data.oneDayShort, today));

⌨️ Terminal

node date-data.js

🖥️ Output

{
  exactly18: '2008-11-23',
  oneDayShort: '2008-11-24',
  tomorrow: '2026-11-24',
  yesterday: '2026-11-22',
  endOfMonth: '2026-11-30',
  leapDay: '2028-02-29',
  in30Days: '2026-12-23'
}
exactly 18 is adult: true
one day short is adult: false

Notice the fixed “today”: a test that calls the real clock gives different results each day and fails around midnight or month ends. Pass “now” in as a parameter, or use fake timers (page.clock in Playwright, mock.timers in Node.js), as the debounce lesson in this module shows.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Create a Date for 15 August 2026 (local time) and print it with toDateString().

Show answer

📄 practice1.js

const d = new Date(2026, 7, 15);   // month 7 = August
console.log(d.toDateString());

🖥️ Output

Sat Aug 15 2026

Q2. Write isValidDate(text) that returns false for strings Date cannot parse.

Show answer

📄 practice2.js

const isValidDate = (text) => !Number.isNaN(new Date(text).getTime());
console.log(isValidDate("2026-11-23"), isValidDate("23/11/2026"), isValidDate("hello"));

// trap: V8 accepts day 31 in February and silently rolls it over
console.log(isValidDate("2026-02-31T00:00:00Z"), new Date("2026-02-31T00:00:00Z").toISOString());

// strict check for YYYY-MM-DD: the date must survive a round trip unchanged
const isRealDay = (ymd) => /^\d{4}-\d{2}-\d{2}$/.test(ymd) && !Number.isNaN(new Date(ymd).getTime()) && new Date(ymd).toISOString().startsWith(ymd);
console.log(isRealDay("2026-02-28"), isRealDay("2026-02-31"), isRealDay("2028-02-29"));

🖥️ Output

true false false
true 2026-03-03T00:00:00.000Z
true false true

A Date that parses is not necessarily the date the user typed. The round-trip check catches 31 February; with Temporal, Temporal.PlainDate.from("2026-02-31", { overflow: "reject" }) throws instead.

Q3. Format 2497 as Indian rupees and 1500000 with Indian digit grouping.

Show answer

📄 practice3.js

console.log(new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(2497));
console.log(new Intl.NumberFormat("en-IN").format(1500000));

🖥️ Output

₹2,497.00
15,00,000

Q4. Show the moment 2026-11-23T12:00:00Z as a time in Mumbai (Asia/Kolkata) and London.

Show answer

📄 practice4.js

const d = new Date("2026-11-23T12:00:00Z");
for (const timeZone of ["Asia/Kolkata", "Europe/London"]) {
  console.log(timeZone, d.toLocaleTimeString("en-GB", { timeZone }));
}

🖥️ Output

Asia/Kolkata 17:30:00
Europe/London 12:00:00

Q5. With Temporal, how many days are there from 2026-11-23 to 2026-12-25?

Show answer

📄 practice5.js

const days = Temporal.PlainDate.from("2026-11-23").until("2026-12-25").days;
console.log(days);

🖥️ Output

32

Q6. List five date-related test cases for a “Date of birth” field.

Show answer

Exactly the minimum age today and one day short; 29 February birthdays (in leap and non-leap years); a future date; an impossible date such as 31 April; different input formats (DD/MM/YYYY vs MM/DD/YYYY) and locales; very old dates (e.g. 1900); and the result around midnight in different time zones (does the age change at local or UTC midnight?).


🧠 MCQ Quiz: Dates, Times and Intl

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does a Date object store internally?
  2. What month is new Date(2026, 1, 10)?
  3. How is new Date("2026-11-23") (date only) interpreted?
  4. What does parsing an invalid string give?
  5. Which method always returns UTC?
  6. How do you compare two Date objects for the same moment?
  7. Which API formats “₹2,497.00” for India?
  8. How do you make formatting independent of the computer’s time zone?
  9. What does Temporal.PlainDate.from("2026-01-31").add({ months: 1 }) return?
  10. Why should date tests use a fixed “today”?

💼 Interview Questions and Answers

Q1. How do time zones cause bugs, and how do you test for them?

A Date is an absolute moment; how it is displayed depends on the time zone. Bugs appear when local and UTC are mixed: a date-only value stored at local midnight becomes the previous day in UTC, reports cut off at the wrong midnight, and daylight-saving transitions make days 23 or 25 hours long. Test by running the app and tests in several time zones (Playwright timezoneId), using times near midnight and DST changes, and checking that APIs exchange ISO strings with offsets.

Q2. What are the problems with the JavaScript Date object?

It is mutable (setters change it in place), months are 0-based, it mixes local and UTC methods, parsing of non-ISO strings is inconsistent, invalid dates do not throw, it has no concept of a date without a time or a time zone other than local and UTC, and arithmetic overflows silently. Temporal was designed to fix these with immutable, explicit types.

Q3. How would you verify a date shown in the UI?

Compute the expected value from the same input data (not a hard-coded string), format it with the same locale and time zone as the app via Intl, and normalise whitespace. Run the browser with a fixed locale and time zone, and control the clock (page.clock.setFixedTime) when the UI shows relative times like “2 days ago”.

Q4. Why does Intl matter for testers in India?

Indian formats differ from US defaults: dates are day-month-year, numbers use lakh/crore grouping (12,34,567), and currency is ₹. An app that formats with en-US or hard-coded patterns shows wrong values to Indian users. Intl with en-IN (or hi-IN) gives correct output, and tests should check those formats explicitly.


Advertisement

❓ Frequently Asked Questions

🤔 Should I use Moment.js?

No for new code: Moment is in maintenance mode. Use Intl for formatting, Temporal where available, or small libraries such as date-fns or Day.js.

🤔 How do I get today’s date as YYYY-MM-DD in local time?

With Temporal: Temporal.Now.plainDateISO().toString(). With Date, toISOString().slice(0, 10) gives the UTC date, which can be yesterday or tomorrow locally; use toLocaleDateString("en-CA") for a local YYYY-MM-DD.

🤔 How do I store dates in a database or API?

As ISO 8601 strings in UTC (2026-11-23T09:30:00Z) or as epoch milliseconds, plus the user’s time zone if you need to display local times later.

🤔 Can I change the time zone of a Date?

No. A Date has no time zone, only a moment. You choose the zone when formatting (Intl timeZone option) or use Temporal.ZonedDateTime.


🏁 Summary

  • A Date is milliseconds since 1970 UTC; months are 0-based; invalid dates have NaN time.
  • Date-only ISO strings are UTC, date-times without Z are local: store and send UTC ISO strings, convert for display only.
  • Use setters on a copy for arithmetic, compare with getTime(), and beware month overflow.
  • Intl formats dates, numbers, currencies, relative times and lists for any locale and time zone.
  • Temporal gives immutable PlainDate, ZonedDateTime, Instant and Duration types; generate date test data from a fixed “today”.

Next, continue with Lesson 66: Memory and Performance.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in