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/time
  • new Date("2024-01-15") — from ISO string
  • new 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

codeTap to expand ⛶
1// Creating dates
2const 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);
6
7// Getters
8console.log(now.getFullYear()); // 2024
9console.log(now.getMonth()); // 0-11 ⚠️
10console.log(now.getDate()); // 1-31
11console.log(now.getDay()); // 0-6 (0 = Sunday)
12console.log(now.getHours());
13console.log(now.getTime()); // Milliseconds since epoch
14
15// Formatting
16console.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"
21
22// Intl.DateTimeFormat
23const formatter = new Intl.DateTimeFormat("en-US", {
24 dateStyle: "full", timeStyle: "short"
25});
26console.log(formatter.format(now));
27
28// Date arithmetic
29const tomorrow = new Date(now);
30tomorrow.setDate(tomorrow.getDate() + 1);
31
32// Difference between dates
33const 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));
37
38// Relative time formatting
39const 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:

  1. Write a function that calculates age from a birthdate
  2. Create a countdown timer to a future date
  3. Write a function that returns "X minutes/hours/days ago" from a timestamp
  4. 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, while new Date('01/15/2024') is local time

  • Date objects are mutable — setDate() modifies the original! Clone first: new Date(original)

  • Using string concatenation for formatting instead of Intl.DateTimeFormat or toLocaleString

  • Not 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.