The Date Object
10 min read
Working with Dates
JavaScript's built-in Date object represents a single moment in time as the number of milliseconds since the Unix epoch (1 January 1970 00:00:00 UTC). Despite its quirks, Date covers most everyday use-cases.
js
// Current date/time
const now = new Date();
// From an ISO string
const d1 = new Date("2025-07-25T10:30:00Z");
// From individual parts (month is 0-indexed!)
const d2 = new Date(2025, 6, 25); // July 25 2025
// From a Unix timestamp (milliseconds)
const d3 = new Date(0); // 1 Jan 1970
console.log(now.toISOString()); // "2025-07-25T..."
console.log(now.toLocaleDateString()); // locale-specificMonths in new Date(year, month, day) are 0-indexed: January = 0, December = 11. This is one of the most common Date gotchas.
Reading and Comparing Dates
js
const d = new Date("2025-07-25T12:00:00Z");
d.getFullYear(); // 2025
d.getMonth(); // 6 (July — 0-indexed)
d.getDate(); // 25 (day of month)
d.getDay(); // 5 (Friday — 0=Sunday)
d.getHours(); // local-time hours
d.getTime(); // Unix ms timestamp
// Arithmetic: subtract two Dates to get milliseconds
const start = new Date("2025-01-01");
const end = new Date("2025-07-25");
const days = (end - start) / (1000 * 60 * 60 * 24);
console.log(Math.round(days)); // 205Formatting with Intl.DateTimeFormat
Prefer Intl.DateTimeFormat (or Date.prototype.toLocaleString) over manual formatting — it handles localisation, time zones, and calendar systems correctly.
js
const formatter = new Intl.DateTimeFormat("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
});
formatter.format(new Date("2025-07-25")); // "25 July 2025"
// Quick one-liner
new Date().toLocaleString("en-US", { timeZone: "America/New_York" });For serious date arithmetic (business days, recurring events, time-zone-aware scheduling), use the Temporal API (now at Stage 3) or a library like date-fns. The built-in Date was designed for simple use-cases and has sharp edges around DST and time zones.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises