⚡ Lesson 25 of 30
Working with Dates & Times
Create, format, compare, and calculate with dates using the Date object and Intl API.
Creating Dates
const now = new Date(); // current date/time
const d1 = new Date("2026-07-04"); // from ISO string
const d2 = new Date(2026, 6, 4); // year, month(0-indexed), day
const ts = Date.now(); // milliseconds since epoch
console.log(now.toISOString()); // "2026-07-04T12:00:00.000Z"
Getting Date Parts
const d = new Date("2026-07-04T15:30:00");
console.log(d.getFullYear()); // 2026
console.log(d.getMonth()); // 6 (July — 0-indexed!)
console.log(d.getDate()); // 4
console.log(d.getDay()); // 6 (Saturday — 0=Sunday)
console.log(d.getHours()); // 15
console.log(d.getMinutes()); // 30
Date Arithmetic
const start = new Date("2026-01-01");
const end = new Date("2026-12-31");
const diffMs = end - start; // timestamps subtract fine
const diffDays = diffMs / (1000 * 60 * 60 * 24);
console.log(diffDays); // 364
// Add 30 days
const future = new Date(start);
future.setDate(future.getDate() + 30);
console.log(future.toDateString()); // "Thu Jan 31 2026"
Formatting with Intl.DateTimeFormat
The Intl API provides locale-aware formatting:
const d = new Date("2026-07-04");
const fmt = new Intl.DateTimeFormat("en-MY", {
dateStyle: "full",
timeStyle: "short",
timeZone: "Asia/Kuala_Lumpur",
});
console.log(fmt.format(d));
// "Saturday, 4 July 2026 at 08:00 am"
Relative Time with Intl.RelativeTimeFormat
const rtf = new Intl.RelativeTimeFormat("en", { numeric:"auto" });
console.log(rtf.format(-1, "day")); // "yesterday"
console.log(rtf.format(3, "week")); // "in 3 weeks"
console.log(rtf.format(-2, "month")); // "2 months ago"