Lesson 44: Mastering JavaScript Date with challenges!

The JavaScript Date
object enables you to work with dates and times in your programs. It can represent timestamps, calculate differences, format time, and manipulate date values.
✅ Basic Syntax:
const now = new Date(); // Current date and time
const birthday = new Date(1995, 11, 17); // Year, Month (0-indexed), Day
const parsed = new Date("2023-06-01T10:00:00Z"); // ISO format (UTC)
✅ Access Date Components
now.getFullYear(); // 2025
now.getMonth(); // 0 (January)
now.getDate(); // 5 (5th day of the month)
now.getDay(); // 4 (Thursday: 0 = Sunday)
now.getHours(); // 18
now.getMinutes(); // 30
now.getSeconds(); // 45
now.getMilliseconds(); // 123
✅ Modify Date Components
now.setFullYear(2030);
now.setMonth(11); // December
now.setDate(1);
now.setHours(0, 0, 0); // Resets time
✅ Timestamps & Parsing
Date.now(); // Current time in ms since Jan 1, 1970
date.getTime(); // Same as above, but on a specific date
Date.parse("2025-06-05T10:00:00Z"); // ms since epoch
✅ Example in Real World
function daysUntilNewYear() {
const now = new Date();
const nextYear = new Date(now.getFullYear() + 1, 0, 1);
const diff = nextYear - now;
return Math.floor(diff / (1000 * 60 * 60 * 24));
}
🔹 2. Fill Any Gaps (Hidden Concepts, Pitfalls, Edge Cases)
🧱 Key Edge Cases
new Date(2025, 0, 32)
→ Autocorrects toFeb 1, 2025
getMonth()
is 0-based butgetDate()
is 1-basedISO strings (
"2024-12-01"
) default to UTC, not local time!
🕳️ Time Zone Quirks
new Date("2024-12-01") // May behave differently across systems
✅ Prefer ISO with T
and Z
:
new Date("2024-12-01T00:00:00Z")
🧠 What Developers Get Wrong
Mixing up
getDay()
(day of week) withgetDate()
(day of month)Forgetting months are 0-indexed
Using
Date
for high-precision timing (useperformance.now
()
instead)Confusing
Date.now
()
withnew Date()
(latter returns object, former returns timestamp)
🔥 Internal Mechanics (Advanced)
Internally stores time as milliseconds since Epoch (UTC)
When calling
.get*()
, the result is adjusted to local timeAutocorrection uses modulo math to overflow into valid dates
🧪 Browser-Specific Behavior
Safari can fail on non-ISO date formats like
"2024/01/01"
Date.parse()
is implementation-dependent — avoid for anything non-ISO
🔹 3. Challenge Me Deeply (10 Problems + 1 Brain Twister)
🟢 Basic
Create a function
isWeekend(date)
that returnstrue
if the given date falls on Saturday or Sunday.Write a function
formatDate(date)
that returns"DD/MM/YYYY"
.
🟢 Basic+
Create a function
getDaysInMonth(year, month)
that returns how many days are in that month.Write a function
isToday(date)
that returns true if the date is today (ignore time).
🟡 Intermediate
Given two date strings, calculate how many full weeks are between them.
Create a countdown function
timeLeft(targetDate)
that returns an object with{days, hours, minutes, seconds}
.Given an array of birthdays, return the next upcoming one.
🔴 Advanced
Create a calendar matrix for a given month (e.g., as an array of weeks, where each week is an array of days).
Create a function
getTimeZoneOffsetInHours()
that returns the user's local timezone offset from UTC.Create a recurring timer that fires a function at exactly 9:00 AM local time every day.
🧩 Brain Twister
- You need to display the same local time (e.g., 6 PM) for users in different time zones.
How can you store and retrieve this in UTC format to ensure consistency?
🔹 4. Interview-Ready Questions
📘 Concept-Based
How does
Date
handle invalid dates?Why are months 0-indexed while days are not?
What’s the difference between
Date.now
()
andnew Date()
?
🧠 Scenario-Based
- You have a UTC timestamp and need to display it in the user's local time with
"HH:MM AM/PM"
format. How would you do it?
🐞 Debugging Questions
Why does
new Date("2022-12-01")
showNov 30
on some machines?Your function that compares dates is failing — what could be the issue?
date1 === date2 // false, even if they represent the same time!
✅ Always compare with .getTime()
or subtract.
✅ Best Practices
✔️ DO:
Use
Date.toISOString()
when sending dates to APIsUse
Date.now
()
for performance timingUse libraries for formatting (e.g.,
Intl.DateTimeFormat
,date-fns
,luxon
)
❌ DON’T:
Use
==
or===
to compareDate
objectsParse date strings in non-ISO formats
Rely on
Date.parse()
across browsers
🔹 5. Real-World Usage
🖥️ Frontend
Countdown timers, calendars, date pickers (e.g., in React apps)
Booking systems, delivery schedules
Event handling (reminders, notifications)
🔧 Backend (Node.js)
Logging, analytics, performance tracking
Time-based job scheduling (e.g., using
cron
,node-schedule
)Authentication expiration checks (
Date.now
() > token.expiry
)
🔍 Frameworks/Libraries
Luxon: Modern immutable alternative
date-fns: Functional and modular
Day.js: Lightweight Moment.js alternative
🧑💻 Open Source Examples
React-Date-Picker
NextAuth.js (uses date comparisons for token expiry)
Jest timers use internal
Date.now
()
mocking
🔹 6. Remember Like a Pro
🧠 Mnemonics
getMonth()
is zero-based → “Months start at Zero”getDay()
returns day of week, not date → D-o-W
🧾 Cheatsheet
Method | Description |
new Date() | Current date/time (local) |
Date.now () | ms since epoch (number) |
getDate() | Day of the month (1-31) |
getDay() | Day of the week (0-6) |
getTime() | Timestamp (ms) |
setFullYear(y) | Changes year |
toISOString() | ISO string (UTC) |
🔹 7. Apply It in a Fun Way
🎯 Mini Project: “World Clock Dashboard 🌍”
Features:
Display live time for 5 cities
Highlight the one closest to the user's timezone
Show whether it’s day/night using background color
✅ Steps:
Use
Intl.DateTimeFormat
to format time based on timezoneStore an array of city names + IANA time zones (
"Asia/Kolkata"
)Update time every second with
setInterval()
Use
Date
andtoLocaleTimeString()
with{ timeZone }
Style background based on local hour
➕ Bonus:
Add sunrise/sunset info from an API
Let user pick cities
➕ (Bonus Section)
❌ Common Mistakes
Using
==
to compare two datesForgetting local vs UTC methods (
getHours()
vsgetUTCHours()
)Not considering Daylight Saving Time (DST) in schedule apps
🧰 Performance Tips
Use
Date.now
()
for fast, accurate timestamps in performance measurementCache date parts if reused — don’t call
.get*()
repeatedly
🛠️ Polyfill Advice
Use date-fns or Intl.DateTimeFormat for reliable formatting
Avoid Moment.js — it's large and legacy
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
