Working with Dates, Timezones & Intl API
Published by Brayan K
By the end of this lesson you'll create, read, and format dates correctly — and show times, currencies, and "3 hours ago" the way each user's country expects.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A timestamp is an instant; a birthday is a calendar date
Choose what the value means before choosing a formatter. A log entry identifies an instant. A birthday identifies calendar fields; it needs a time and zone before it identifies an instant. Converting every date-only field to midnight UTC can display the previous date to a reader west of UTC.
function calendarParts(instant, timeZone) {
const formatter = new Intl.DateTimeFormat("en-GB", {
timeZone, calendar: "gregory", numberingSystem: "latn",
year: "numeric", month: "2-digit", day: "2-digit"
});
const values = Object.fromEntries(formatter.formatToParts(instant)
.filter(part => part.type !== "literal").map(part => [part.type, part.value]));
return [values.year, values.month, values.day].join("-");
}
// A fixed instant keeps this example independent of the current clock.
const instant = new Date("2024-01-01T00:30:00Z");
// Formatting changes the display, not the stored instant.
const before = instant.getTime();
console.log(calendarParts(instant, "UTC"));
console.log(calendarParts(instant, "America/New_York"));
console.log(instant.getTime() === before);
// ✅ Expected output:
// 2024-01-01
// 2023-12-31
// trueDate stores a millisecond timestamp, not the original offset or a named time zone. Local getters use the host zone; UTC getters do not. Use an explicit offset or Z when the contract requires an instant. Keep a date-only business value in a validated calendar representation when that is what the product means.
const a = new Date("2024-06-01T12:00:00Z");
const b = new Date("2024-06-01T14:00:00+02:00");
console.log(a.getTime() === b.getTime());
console.log(b.toISOString());
// ✅ Expected output:
// true
// 2024-06-01T12:00:00.000ZParsing and validation are separate decisions
The standardized date-only form without an offset is interpreted as UTC; a date-time without an offset is interpreted in the host local zone. A slash-separated date is not a portable interchange contract. Intl formats values; it does not parse its display strings back into dates.
const date = new Date("2024-02-29");
console.log(date.toISOString());
console.log(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
// ✅ Expected output:
// 2024-02-29T00:00:00.000Z
// 2024 1 29Numeric construction and setters normalize overflow. That is useful for arithmetic but insufficient for validating a user-entered date. Months in these Date APIs start at zero. Numeric years zero through 99 also use the legacy 1900 through 1999 mapping; a strict parser needs an explicit supported-year contract.
const value = new Date(Date.UTC(2024, 1, 30));
console.log(value.toISOString().slice(0, 10));
console.log(value.getUTCMonth() === 1 && value.getUTCDate() === 30);
console.log(new Date(Date.UTC(24, 0, 1)).getUTCFullYear());
// ✅ Expected output:
// 2024-03-01
// false
// 1924const value = new Date("not-a-date");
console.log(value instanceof Date, Number.isNaN(value.getTime()));
value.toISOString();
// ✅ Expected output:
// true true
// ✅ Expected error:
// RangeError: Invalid time valueChecking instanceof Date alone accepts invalid dates. Check the timestamp, and also compare the requested calendar fields when validating a date-only input. The brief rejects February 30 before it can quietly become March.
Elapsed durations and calendar arithmetic answer different questions
Adding 86,400,000 milliseconds means exactly 24 hours, not necessarily tomorrow at the same local wall time. Daylight-saving transitions can change a local day’s duration. Named-zone scheduling needs a policy for nonexistent or repeated wall times.
const start = new Date("2024-03-10T00:00:00-05:00");
const end = new Date("2024-03-11T00:00:00-04:00");
console.log((end.getTime() - start.getTime()) / 3_600_000);
const exactly24Hours = new Date(start.getTime() + 86_400_000);
console.log(exactly24Hours.toISOString());
console.log(exactly24Hours.getTime() === end.getTime());
// ✅ Expected output:
// 23
// 2024-03-11T05:00:00.000Z
// falseThese explicit offsets describe a fixed historical example without relying on the host zone. An offset is not a future rule set for a city. DateTimeFormat displays instants in named zones; it does not resolve arbitrary local wall-time fields into an instant.
const original = new Date("2024-01-31T00:00:00Z");
const alias = original;
const copy = new Date(original.getTime());
original.setUTCMonth(1);
console.log(alias === original, alias.toISOString().slice(0, 10));
console.log(copy.toISOString().slice(0, 10));
// ✅ Expected output:
// true 2024-03-02
// 2024-01-31Setting February preserves day 31 first, then normalizes overflow. Decide whether “one month later” means rollover, rejection or clamping. Deep Copy vs Shallow Copy & Data Structures owns reference-copy rules; here the consequence is an unexpected calendar calculation.
Format for a reader and serialize for a machine
Specify locale, timeZone, calendar and numberingSystem when a test depends on them. Even an explicit locale can have punctuation or spacing changes across locale-data versions. Use ISO text for interchange; use formatToParts for named display components instead of splitting punctuation.
function calendarParts(instant, timeZone) {
const formatter = new Intl.DateTimeFormat("en-GB", {
timeZone, calendar: "gregory", numberingSystem: "latn",
year: "numeric", month: "2-digit", day: "2-digit"
});
const values = Object.fromEntries(formatter.formatToParts(instant)
.filter(part => part.type !== "literal").map(part => [part.type, part.value]));
return [values.year, values.month, values.day].join("-");
}
const instant = new Date("2024-12-31T23:30:00Z");
console.log(calendarParts(instant, "UTC"));
console.log(calendarParts(instant, "Asia/Tokyo"));
// ✅ Expected output:
// 2024-12-31
// 2025-01-01Reuse a formatter when its options are the same. This is a design choice, not a measured speed claim. These panels print selected numeric parts rather than promising a particular localized separator or spacing.
const formatter = new Intl.NumberFormat("en-GB", {
style: "currency", currency: "GBP", currencyDisplay: "code",
minimumFractionDigits: 2, maximumFractionDigits: 2
});
const amount = 12.345;
const parts = formatter.formatToParts(amount);
console.log(parts.find(part => part.type === "integer").value);
console.log(parts.find(part => part.type === "fraction").value);
console.log(parts.find(part => part.type === "currency").value);
console.log(amount === 12.345);
// ✅ Expected output:
// 12
// 35
// GBP
// trueCurrency formatting does not convert currencies or make floating-point arithmetic exact. Keep monetary arithmetic and domain rounding separate from presentation. Numbers & Math owns numeric representation.
const formatter = new Intl.RelativeTimeFormat("en", { numeric: "always" });
for (const count of [-3, 2]) {
const parts = formatter.formatToParts(count, "hour");
console.log(parts.find(part => part.type === "integer").value);
}
console.log(formatter.resolvedOptions().numeric);
// ✅ Expected output:
// 3
// 2
// alwaysRelativeTimeFormat does not choose a unit, read the clock or schedule updates. Negative counts mean past and positive counts mean future. Define rounding and update policy in your code; a relative label grows stale if nothing recomputes it.
Inject the reference instant into duration calculations
function completedMinutes(since, reference) {
if (!Number.isFinite(since) || !Number.isFinite(reference))
throw new TypeError("timestamps must be finite numbers");
return Math.trunc((reference - since) / 60_000);
}
const start = Date.parse("2024-01-01T00:00:00Z");
console.log(completedMinutes(start, start + 119_999));
console.log(completedMinutes(start, start - 120_000));
// ✅ Expected output:
// 1
// -2This counts completed elapsed minutes, not calendar age. Birthday-based age and legal deadlines have domain rules beyond timestamp subtraction. An explicit reference keeps tests reproducible. Pure Functions, Immutability & Side Effects owns hidden-dependency discipline.
Guided exercise: copy before advancing a calendar day
Use the three literal hints to copy the timestamp, change UTC calendar fields and retain the original date.
const source = new Date("2024-02-28T00:00:00Z");
const next = new Date(source.___()); // 👉 replace ___ with getTime
next.___(next.getUTCDate() + 1); // 👉 replace ___ with setUTCDate
console.log(next.___().slice(0, 10)); // 👉 replace ___ with toISOString
console.log(source.toISOString().slice(0, 10));
// ✅ Expected output:
// 2024-02-29
// 2024-02-28Independent brief: shift a validated date-only value
Implement shiftCalendarDate(text, days). Accept exactly YYYY-MM-DD in years 2000 through 2099 and an integer shift from -366 through 366. Reject impossible dates, extra whitespace and a result outside those years. Return a new YYYY-MM-DD string. No timestamps, time zones or localized strings are accepted.
Use UTC fields solely as an arithmetic representation of this Gregorian calendar value. The result remains date-only, not an appointment instant. Compare all original fields after construction before applying the shift.
function shiftCalendarDate(text, days) {
if (typeof text !== "string" || !/^20\d{2}-\d{2}-\d{2}$/.test(text))
throw new TypeError("date must use YYYY-MM-DD in 2000..2099");
if (!Number.isInteger(days) || days < -366 || days > 366)
throw new RangeError("days must be an integer in -366..366");
const [year, month, day] = text.split("-").map(Number);
const value = new Date(Date.UTC(year, month - 1, day));
// Construction normalizes overflow; compare every original calendar field.
if (value.getUTCFullYear() !== year || value.getUTCMonth() !== month - 1 ||
value.getUTCDate() !== day)
throw new RangeError("date is not a real calendar day");
value.setUTCDate(value.getUTCDate() + days);
if (value.getUTCFullYear() < 2000 || value.getUTCFullYear() > 2099)
throw new RangeError("result leaves 2000..2099");
return value.toISOString().slice(0, 10);
}
for (const [text, days] of [["2024-02-28", 1], ["2023-02-28", 1], ["2024-01-01", -1], ["2000-02-29", 366]]) {
console.log(shiftCalendarDate(text, days));
}
for (const [text, days] of [["2023-02-29", 1], ["2024-04-31", 0], ["2000-01-01", -1], ["2024-01-01", 1.5]]) {
try { shiftCalendarDate(text, days); }
catch (error) { console.log(error.name, error.message); }
}
// ✅ Expected output:
// 2024-02-29
// 2023-03-01
// 2023-12-31
// 2001-03-01
// RangeError date is not a real calendar day
// RangeError date is not a real calendar day
// RangeError result leaves 2000..2099
// RangeError days must be an integer in -366..366Reference notes
The Date reference documents parsing, normalization and offset transitions. The DateTimeFormat reference covers locale options and named parts. Examples use fixed dates and never read the current clock.
Practice quiz
What does this complete program print? const a=new Date("2024-01-01T00:00:00Z"),b=new Date("2024-01-01T01:00:00+01:00");console.log(a.getTime()===b.getTime());
- true
- false
- undefined
- TypeError
Answer: true. The offsets identify the same instant.
What does this complete program print? console.log(new Date("2024-02-29").getUTCMonth());
- 2
- 1
- 3
- 29
Answer: 1. Date month indexes begin with January at zero.
What does this complete program print? const value=new Date(Date.UTC(2023,1,29));console.log(value.toISOString().slice(0,10));
- 2023-02-29
- Invalid Date
- 2023-03-01
- 2024-02-29
Answer: 2023-03-01. The constructor normalizes the nonexistent day into March.
What does this complete program print? const value=new Date("bad");console.log(value instanceof Date,Number.isNaN(value.getTime()));
- false true
- true false
- false false
- true true
Answer: true true. Invalid Date has a NaN timestamp.
What does this complete program print? const a=new Date("2024-01-01T00:00:00Z");const b=a;b.setUTCDate(2);console.log(a.getUTCDate());
- 2
- 1
- 0
- undefined
Answer: 2. Both references point to the mutated Date.
What does this complete program print? const a=Date.parse("2024-03-10T00:00:00-05:00"),b=Date.parse("2024-03-11T00:00:00-04:00");console.log((b-a)/3600000);
- 24
- 23
- 25
- 0
Answer: 23. The explicit offsets span 23 elapsed hours.
What does this complete program print? const source=new Date("2024-01-31T00:00:00Z");const copy=new Date(source.getTime());copy.setUTCDate(1);console.log(source.getUTCDate(),copy.getUTCDate());
- 1 1
- 31 31
- 31 1
- 1 31
Answer: 31 1. Copying the timestamp creates an independent Date.
What does this complete program print? console.log(new Date(Date.UTC(24,0,1)).getUTCFullYear());
- 24
- 2024
- 0
- 1924
Answer: 1924. The legacy numeric year rule maps 24 to 1924.
Continue this course
- Previous: Regular Expressions Advanced Techniques
- Next: JavaScript Design Patterns (Factory, Singleton, Strategy, etc.) — Apply advanced GoF patterns and architectural patterns to real JS apps
- Quick reference: JavaScript cheat sheet