Date & Time Handling
📖 Concept
JavaScript's Date object handles dates and times. While functional, it has many quirks and limitations — which is why libraries like date-fns and Temporal (upcoming API) exist.
Creating dates:
new Date()— current date/timenew Date("2024-01-15")— from ISO stringnew Date(2024, 0, 15)— from parts (months are 0-indexed!)
Key gotcha: Months are 0-indexed! January = 0, December = 11.
🏠 Real-world analogy: JavaScript's Date is like an old analog watch — it tells time, but setting it is fiddly, time zones are a nightmare, and you often wish you had a modern digital watch (Temporal API).
💻 Code Example
1// Creating dates2const now = new Date();3const specific = new Date("2024-06-15T10:30:00");4const fromParts = new Date(2024, 5, 15); // June 15! (month is 0-indexed)5const fromTimestamp = new Date(1718438400000);67// Getters8console.log(now.getFullYear()); // 20249console.log(now.getMonth()); // 0-11 ⚠️10console.log(now.getDate()); // 1-3111console.log(now.getDay()); // 0-6 (0 = Sunday)12console.log(now.getHours());13console.log(now.getTime()); // Milliseconds since epoch1415// Formatting16console.log(now.toLocaleDateString("en-US")); // "1/15/2024"17console.log(now.toISOString()); // "2024-01-15T..."18console.log(now.toLocaleString("en-US", {19 weekday: "long", year: "numeric", month: "long", day: "numeric"20})); // "Monday, January 15, 2024"2122// Intl.DateTimeFormat23const formatter = new Intl.DateTimeFormat("en-US", {24 dateStyle: "full", timeStyle: "short"25});26console.log(formatter.format(now));2728// Date arithmetic29const tomorrow = new Date(now);30tomorrow.setDate(tomorrow.getDate() + 1);3132// Difference between dates33const start = new Date("2024-01-01");34const end = new Date("2024-12-31");35const diffMs = end - start;36const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));3738// Relative time formatting39const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });40console.log(rtf.format(-1, "day")); // "yesterday"41console.log(rtf.format(2, "hour")); // "in 2 hours"
🏋️ Practice Exercise
Mini Exercise:
- Write a function that calculates age from a birthdate
- Create a countdown timer to a future date
- Write a function that returns "X minutes/hours/days ago" from a timestamp
- Build a simple calendar for the current month
⚠️ Common Mistakes
Months are 0-indexed:
new Date(2024, 1, 1)is February 1st, NOT January!new Date('2024-01-15')may be interpreted as UTC, whilenew Date('01/15/2024')is local timeDate objects are mutable —
setDate()modifies the original! Clone first:new Date(original)Using string concatenation for formatting instead of
Intl.DateTimeFormatortoLocaleStringNot accounting for daylight saving time when doing date arithmetic
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Date & Time Handling. Login to unlock this feature.