JavaScript Date Confusion: Zero-Based Months

✅ JavaScript Output — Why This Date Confuses Almost Everyone This morning’s code was: const date = new Date(2025, 1, 1); console.log(date.getMonth()); console.log(date.getDate()); console.log(date.getFullYear()); 💡 Correct Output 1 1 2025 Now let’s understand why this happens 👇 🧠 Simple Explanation : 🔹 How new Date(year, month, day) really works JavaScript’s Date constructor follows this rule: 👉 Month is ZERO-based That means: 0 → January 1 → February 2 → March … 11 → December So when you write: new Date(2025, 1, 1) JavaScript reads it as: 👉 1st February 2025, not January. 🔹 Line 1: date.getMonth() Since February is internally stored as 1: getMonth() → 1 ✔ Output: 1 🔹 Line 2: date.getDate() This returns the day of the month, and here it is clearly: 1 ✔ Output: 1 🔹 Line 3: date.getFullYear() Year is straightforward: 2025 ✔ Output: 2025 🎯 Key Takeaways : JavaScript months are 0-based Days and years are 1-based new Date(2025, 1, 1) = Feb 1, 2025 This causes many real-world bugs if not remembered 📌 That’s why many developers prefer libraries or careful handling when working with dates 💬 Your Turn Did you expect 1 to mean February? 😄 Comment “Tricky 😮” or “Knew this 👍” #JavaScript #FrontendDevelopment #LearnJS #CodingInterview #Dates #TechWithVeera #WebDevelopment #100DaysOfCode

  • graphical user interface

To view or add a comment, sign in

Explore content categories