JavaScript Tutorial

Date Object in JavaScript: Complete Guide with Examples

Master the JavaScript Date object — creating dates, getting and setting date parts, formatting, date arithmetic, comparing dates, real-world examples, and best practices.

Welcome back! 👋 We're now stepping into the JavaScript Objects section — built-in objects that JavaScript gives you out of the box to handle common tasks. We're starting with one you'll need in almost every real project — the Date object!

Whether you're building a booking system, displaying timestamps, calculating deadlines, formatting dates for an API, or showing "posted 3 hours ago" — the Date object is your tool. Let's master it completely!


What is the Date Object?

The Date object is a built-in JavaScript object that represents a single point in time. Internally, it stores time as the number of milliseconds since January 1, 1970, 00:00:00 UTC — known as the Unix Epoch.

let now = new Date();
console.log(now);
// Output: Fri Feb 13 2024 10:30:45 GMT+0530 (India Standard Time)

Creating Dates

Current Date and Time

let now = new Date();
console.log(now); // Current date and time

From a Date String

let d1 = new Date("2024-02-13");           // YYYY-MM-DD
let d2 = new Date("2024-02-13T10:30:00"); // YYYY-MM-DDTHH:MM:SS
let d3 = new Date("February 13, 2024");   // Long form

console.log(d1); // Tue Feb 13 2024 05:30:00 ...
console.log(d2); // Tue Feb 13 2024 10:30:00 ...

From Year, Month, Day, Hour, Minute, Second

// new Date(year, monthIndex, day, hours, minutes, seconds)
// ⚠️ Month is 0-indexed: January = 0, December = 11

let d = new Date(2024, 1, 13, 10, 30, 0);
//              year  Feb day  hr  min  sec

console.log(d); // Tue Feb 13 2024 10:30:00

From Milliseconds (Unix Timestamp)

let d = new Date(0);          // Unix Epoch start
console.log(d);               // Thu Jan 01 1970 ...

let d2 = new Date(1707820800000); // A specific timestamp
console.log(d2);

Date.now() — Current Timestamp in Milliseconds

let timestamp = Date.now();
console.log(timestamp); // e.g. 1707820800000

// Great for measuring performance
let start = Date.now();
// ... some code ...
let end = Date.now();
console.log(`Took ${end - start}ms`);

Getting Date Parts

Use getter methods to extract individual parts of a date.

let date = new Date("2024-02-13T10:30:45");

console.log(date.getFullYear());  // 2024
console.log(date.getMonth());     // 1 (February — 0-indexed!)
console.log(date.getDate());      // 13 (day of month)
console.log(date.getDay());       // 2 (Tuesday — 0=Sun, 6=Sat)
console.log(date.getHours());     // 10
console.log(date.getMinutes());   // 30
console.log(date.getSeconds());   // 45
console.log(date.getTime());      // milliseconds since epoch

⚠️ Month is 0-Indexed — Most Common Gotcha!

let date = new Date("2024-02-13");

// ❌ Wrong — getMonth() returns 1, not 2
console.log(`Month: ${date.getMonth()}`);   // 1 (NOT February's 2!)

// ✅ Always add 1 for human-readable month
console.log(`Month: ${date.getMonth() + 1}`); // 2 ✅

// ✅ Or use an array to get month name
let months = ["January","February","March","April","May","June",
              "July","August","September","October","November","December"];
console.log(months[date.getMonth()]); // "February" ✅

Day Names

let days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
let date = new Date("2024-02-13");

console.log(days[date.getDay()]); // "Tuesday"

All Getters at a Glance

let date = new Date("2024-02-13T10:30:45");

let info = {
  year:    date.getFullYear(),       // 2024
  month:   date.getMonth() + 1,      // 2 (add 1!)
  day:     date.getDate(),           // 13
  weekday: date.getDay(),            // 2
  hours:   date.getHours(),          // 10
  minutes: date.getMinutes(),        // 30
  seconds: date.getSeconds(),        // 45
  ms:      date.getMilliseconds(),   // 0
  timestamp: date.getTime(),         // milliseconds
};

console.log(info);

Setting Date Parts

Use setter methods to change parts of an existing date.

let date = new Date("2024-02-13");

date.setFullYear(2025);
date.setMonth(11);   // December (0-indexed)
date.setDate(25);    // Christmas!
date.setHours(9);
date.setMinutes(0);

console.log(date); // Thu Dec 25 2025 09:00:00

Practical — Move a Date Forward

let deadline = new Date("2024-02-13");
deadline.setDate(deadline.getDate() + 30); // Add 30 days

console.log(deadline); // Fri Mar 14 2024 — handles month overflow ✅

Formatting Dates

JavaScript has several built-in ways to format dates.

Built-in Format Methods

let date = new Date("2024-02-13T10:30:45");

console.log(date.toString());
// "Tue Feb 13 2024 10:30:45 GMT+0530"

console.log(date.toDateString());
// "Tue Feb 13 2024"

console.log(date.toTimeString());
// "10:30:45 GMT+0530"

console.log(date.toISOString());
// "2024-02-13T05:00:45.000Z" — UTC format, great for APIs

console.log(date.toLocaleDateString());
// "2/13/2024" — locale-dependent

console.log(date.toLocaleTimeString());
// "10:30:45 AM"

console.log(date.toLocaleString());
// "2/13/2024, 10:30:45 AM"

toLocaleDateString() with Options — Powerful Formatting

let date = new Date("2024-02-13");

// Indian English format
console.log(date.toLocaleDateString("en-IN", {
  day:   "numeric",
  month: "long",
  year:  "numeric",
}));
// "13 February 2024"

// Short with weekday
console.log(date.toLocaleDateString("en-US", {
  weekday: "long",
  day:     "numeric",
  month:   "short",
  year:    "numeric",
}));
// "Tuesday, Feb 13, 2024"

// Numeric only
console.log(date.toLocaleDateString("en-IN", {
  day:   "2-digit",
  month: "2-digit",
  year:  "numeric",
}));
// "13/02/2024"

Custom Format Function

function formatDate(date, format = "DD/MM/YYYY") {
  let dd   = String(date.getDate()).padStart(2, "0");
  let mm   = String(date.getMonth() + 1).padStart(2, "0");
  let yyyy = date.getFullYear();

  return format
    .replace("DD",   dd)
    .replace("MM",   mm)
    .replace("YYYY", yyyy);
}

let date = new Date("2024-02-13");

console.log(formatDate(date));              // "13/02/2024"
console.log(formatDate(date, "YYYY-MM-DD")); // "2024-02-13"
console.log(formatDate(date, "DD-MM-YYYY")); // "13-02-2024"

Date Arithmetic

Since dates are stored as milliseconds, you can do math with them.

Difference Between Two Dates

let start = new Date("2024-01-01");
let end   = new Date("2024-02-13");

let diffMs   = end - start;                 // difference in milliseconds
let diffDays = diffMs / (1000 * 60 * 60 * 24); // convert to days

console.log(`${diffDays} days between dates`); // 43 days

Add Days / Months / Years

function addDays(date, days) {
  let result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

function addMonths(date, months) {
  let result = new Date(date);
  result.setMonth(result.getMonth() + months);
  return result;
}

function addYears(date, years) {
  let result = new Date(date);
  result.setFullYear(result.getFullYear() + years);
  return result;
}

let today = new Date("2024-02-13");

console.log(addDays(today, 30).toDateString());    // "Fri Mar 14 2024"
console.log(addMonths(today, 3).toDateString());   // "Sun May 13 2024"
console.log(addYears(today, 1).toDateString());    // "Wed Feb 13 2025"

Days Until a Date

function daysUntil(targetDate) {
  let now    = new Date();
  now.setHours(0, 0, 0, 0); // normalize to midnight

  let target = new Date(targetDate);
  target.setHours(0, 0, 0, 0);

  let diffMs   = target - now;
  let diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));

  if (diffDays < 0)  return `${Math.abs(diffDays)} days ago`;
  if (diffDays === 0) return "Today!";
  return `${diffDays} days away`;
}

console.log(daysUntil("2024-12-25")); // "X days away" (Christmas)
console.log(daysUntil("2024-01-01")); // "X days ago"

Comparing Dates

let date1 = new Date("2024-01-01");
let date2 = new Date("2024-06-15");
let date3 = new Date("2024-01-01");

// ✅ Compare with > < >= <=
console.log(date1 < date2);  // true
console.log(date2 > date1);  // true

// ⚠️ Don't use == or === — compares object references!
console.log(date1 == date3);  // false ❌ (different objects)
console.log(date1 === date3); // false ❌

// ✅ Compare timestamps for equality
console.log(date1.getTime() === date3.getTime()); // true ✅

// ✅ Or compare ISO strings
console.log(date1.toISOString() === date3.toISOString()); // true ✅

Sort Dates

let dates = [
  new Date("2024-06-15"),
  new Date("2024-01-01"),
  new Date("2024-12-25"),
  new Date("2024-03-08"),
];

// Ascending (earliest first)
dates.sort((a, b) => a - b);
dates.forEach(d => console.log(d.toDateString()));
// Mon Jan 01 2024
// Fri Mar 08 2024
// Sat Jun 15 2024
// Wed Dec 25 2024

Real-World Examples

Example 1: Age Calculator

function calculateAge(birthDateStr) {
  let birthDate = new Date(birthDateStr);
  let today     = new Date();

  let age = today.getFullYear() - birthDate.getFullYear();

  // Adjust if birthday hasn't happened yet this year
  let monthDiff = today.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }

  return age;
}

console.log(`Age: ${calculateAge("1999-05-15")} years`);
console.log(`Age: ${calculateAge("2000-12-31")} years`);

Example 2: Relative Time — "Posted X ago"

function timeAgo(dateStr) {
  let past    = new Date(dateStr);
  let now     = new Date();
  let diffSec = Math.floor((now - past) / 1000);

  if (diffSec < 60)       return `${diffSec} seconds ago`;
  if (diffSec < 3600)     return `${Math.floor(diffSec / 60)} minutes ago`;
  if (diffSec < 86400)    return `${Math.floor(diffSec / 3600)} hours ago`;
  if (diffSec < 2592000)  return `${Math.floor(diffSec / 86400)} days ago`;
  if (diffSec < 31536000) return `${Math.floor(diffSec / 2592000)} months ago`;
  return `${Math.floor(diffSec / 31536000)} years ago`;
}

// Simulate posts
let posts = [
  { title: "Intro to JavaScript",    posted: new Date(Date.now() - 45000)     }, // 45s
  { title: "Arrow Functions Guide",  posted: new Date(Date.now() - 900000)    }, // 15min
  { title: "Working with Arrays",    posted: new Date(Date.now() - 18000000)  }, // 5hr
  { title: "Objects Deep Dive",      posted: new Date(Date.now() - 172800000) }, // 2 days
];

posts.forEach(({ title, posted }) => {
  console.log(`"${title}" — ${timeAgo(posted)}`);
});
// Output:
// "Intro to JavaScript" — 45 seconds ago
// "Arrow Functions Guide" — 15 minutes ago
// "Working with Arrays" — 5 hours ago
// "Objects Deep Dive" — 2 days ago

Example 3: Booking System — Check Availability

function isDateAvailable(checkIn, checkOut, bookings) {
  let start = new Date(checkIn);
  let end   = new Date(checkOut);

  for (let booking of bookings) {
    let bStart = new Date(booking.checkIn);
    let bEnd   = new Date(booking.checkOut);

    // Overlap if start < bEnd AND end > bStart
    if (start < bEnd && end > bStart) {
      return false; // Conflict!
    }
  }
  return true;
}

let existingBookings = [
  { checkIn: "2024-03-01", checkOut: "2024-03-05" },
  { checkIn: "2024-03-10", checkOut: "2024-03-15" },
  { checkIn: "2024-03-20", checkOut: "2024-03-25" },
];

let requests = [
  { checkIn: "2024-03-06", checkOut: "2024-03-09" }, // Available
  { checkIn: "2024-03-03", checkOut: "2024-03-07" }, // Conflict!
  { checkIn: "2024-03-16", checkOut: "2024-03-19" }, // Available
];

requests.forEach(({ checkIn, checkOut }) => {
  let available = isDateAvailable(checkIn, checkOut, existingBookings);
  console.log(`${checkIn}${checkOut}: ${available ? "✅ Available" : "❌ Not Available"}`);
});
// Output:
// 2024-03-06 → 2024-03-09: ✅ Available
// 2024-03-03 → 2024-03-07: ❌ Not Available
// 2024-03-16 → 2024-03-19: ✅ Available

Example 4: Event Countdown Timer

function eventCountdown(eventName, eventDate) {
  let now    = new Date();
  let target = new Date(eventDate);
  let diff   = target - now;

  if (diff <= 0) {
    console.log(`🎉 ${eventName} has already happened!`);
    return;
  }

  let days    = Math.floor(diff / (1000 * 60 * 60 * 24));
  let hours   = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = Math.floor((diff % (1000 * 60)) / 1000);

  console.log(`⏳ ${eventName}`);
  console.log(`   ${days}d ${hours}h ${minutes}m ${seconds}s remaining`);
}

eventCountdown("New Year 2025",        "2025-01-01T00:00:00");
eventCountdown("Republic Day",         "2025-01-26T00:00:00");
eventCountdown("Independence Day",     "2025-08-15T00:00:00");
// Output:
// ⏳ New Year 2025
//    XXd XXh XXm XXs remaining

Example 5: Work Hours Calculator

function calcWorkHours(checkIn, checkOut) {
  let start = new Date(checkIn);
  let end   = new Date(checkOut);

  let diffMs      = end - start;
  let totalMins   = Math.floor(diffMs / (1000 * 60));
  let hours       = Math.floor(totalMins / 60);
  let minutes     = totalMins % 60;
  let overtime    = Math.max(0, totalMins - 8 * 60);
  let overtimeHrs = Math.floor(overtime / 60);
  let overtimeMins = overtime % 60;

  return { hours, minutes, overtime: `${overtimeHrs}h ${overtimeMins}m` };
}

let attendance = [
  { name: "Mihir", checkIn: "2024-02-13T09:00:00", checkOut: "2024-02-13T18:30:00" },
  { name: "Priya", checkIn: "2024-02-13T09:30:00", checkOut: "2024-02-13T17:00:00" },
  { name: "Rahul", checkIn: "2024-02-13T08:00:00", checkOut: "2024-02-13T20:00:00" },
];

console.log("=== ⏰ Work Hours Report ===");
for (let { name, checkIn, checkOut } of attendance) {
  let { hours, minutes, overtime } = calcWorkHours(checkIn, checkOut);
  console.log(`${name.padEnd(8)}: ${hours}h ${minutes}m worked | Overtime: ${overtime}`);
}
// Output:
// Mihir   : 9h 30m worked | Overtime: 1h 30m
// Priya   : 7h 30m worked | Overtime: 0h 0m
// Rahul   : 12h 0m worked | Overtime: 4h 0m

Common Mistakes

Mistake 1: Month is 0-Indexed

// ❌ Creating February — month must be 1, NOT 2!
let feb = new Date(2024, 2, 13); // This is March!
console.log(feb.toDateString()); // "Wed Mar 13 2024" ❌

// ✅ February = month index 1
let feb = new Date(2024, 1, 13);
console.log(feb.toDateString()); // "Tue Feb 13 2024" ✅

// ✅ Or use ISO string to avoid confusion
let feb2 = new Date("2024-02-13"); // Clear and safe ✅

Mistake 2: Comparing Dates with ===

let d1 = new Date("2024-02-13");
let d2 = new Date("2024-02-13");

// ❌ === compares object references — always false!
console.log(d1 === d2); // false ❌

// ✅ Compare timestamps
console.log(d1.getTime() === d2.getTime()); // true ✅

// ✅ Or compare with > or <
console.log(d1 >= d2); // true ✅

Mistake 3: Mutating the Original Date

let original = new Date("2024-01-01");

// ❌ This modifies the original!
function addDays(date, days) {
  date.setDate(date.getDate() + days); // Mutates original!
  return date;
}

let future = addDays(original, 30);
console.log(original.toDateString()); // "Thu Feb 01 2024" — changed! ❌

// ✅ Always create a new Date object
function addDays(date, days) {
  let result = new Date(date); // Copy
  result.setDate(result.getDate() + days);
  return result;
}

Mistake 4: Forgetting to Normalize for Day Comparisons

let today     = new Date();         // Has time: 10:30:45
let birthday  = new Date("2024-02-13"); // 00:00:00

// ❌ Comparison includes time — might give wrong result
console.log(today > birthday); // could be wrong for same day!

// ✅ Normalize time to midnight before comparing dates
let normalizedToday = new Date(today);
normalizedToday.setHours(0, 0, 0, 0);

let normalizedBirthday = new Date(birthday);
normalizedBirthday.setHours(0, 0, 0, 0);

console.log(normalizedToday.getTime() === normalizedBirthday.getTime()); // reliable ✅

Practical Exercise

Create a file called date-object.js:

// 🎯 Date Object Practice

// 1. Today's full info
console.log("=== 📅 Today's Date Info ===");
let today = new Date();
let days   = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
let months = ["January","February","March","April","May","June",
              "July","August","September","October","November","December"];

console.log(`Full Date:   ${today.toDateString()}`);
console.log(`Day:         ${days[today.getDay()]}`);
console.log(`Date:        ${today.getDate()} ${months[today.getMonth()]} ${today.getFullYear()}`);
console.log(`Time:        ${today.toLocaleTimeString()}`);
console.log(`ISO:         ${today.toISOString()}`);
console.log(`Timestamp:   ${today.getTime()}`);


// 2. Important dates countdown
console.log("\n=== ⏳ Upcoming Events ===");
let events = [
  { name: "New Year 2025",    date: "2025-01-01" },
  { name: "Valentine's Day",  date: "2025-02-14" },
  { name: "Holi",             date: "2025-03-14" },
  { name: "Independence Day", date: "2025-08-15" },
];

let now = new Date();
now.setHours(0, 0, 0, 0);

events.forEach(({ name, date }) => {
  let target   = new Date(date);
  let diffMs   = target - now;
  let diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
  let label    = diffDays > 0 ? `${diffDays} days away` : diffDays === 0 ? "Today! 🎉" : "Passed";
  console.log(`  ${name.padEnd(20)}: ${label}`);
});


// 3. Employee birthday checker
console.log("\n=== 🎂 Birthday Checker ===");
let employees = [
  { name: "Mihir",  dob: "1999-02-13" },
  { name: "Priya",  dob: "1998-06-15" },
  { name: "Rahul",  dob: "2000-12-25" },
  { name: "Sara",   dob: "1997-08-10" },
];

let currentMonth = new Date().getMonth();
let currentDay   = new Date().getDate();

employees.forEach(({ name, dob }) => {
  let birth = new Date(dob);
  let age   = new Date().getFullYear() - birth.getFullYear();

  let isBirthday =
    birth.getMonth() === currentMonth &&
    birth.getDate()  === currentDay;

  let birthdayThis = new Date(
    new Date().getFullYear(), birth.getMonth(), birth.getDate()
  );
  let daysUntil = Math.ceil((birthdayThis - now) / (1000 * 60 * 60 * 24));

  console.log(
    `${name.padEnd(8)}: Age ${age} | DOB: ${birth.toLocaleDateString("en-IN")}` +
    ` | ${isBirthday ? "🎉 Happy Birthday!" : `Birthday in ${daysUntil > 0 ? daysUntil : 365 + daysUntil} days`}`
  );
});

Run it:

node date-object.js

Key Takeaways

Congratulations! 🎉 You now fully understand the JavaScript Date object.

Create dates with new Date(), date strings, year/month/day params, or milliseconds.

Month is 0-indexed — always add 1 when displaying. January = 0, December = 11.

GettersgetFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes(), getSeconds(), getTime().

SetterssetFullYear(), setMonth(), setDate(), setHours() etc. — always copy first!

FormattingtoDateString(), toISOString(), toLocaleDateString() with locale options.

Date math — subtract dates to get milliseconds, convert to days/hours/minutes.

Never use === to compare dates — use .getTime() or > / < operators.

Normalize to midnight (setHours(0,0,0,0)) before comparing calendar dates.


Best Practices

  1. ✅ Always use ISO string format "YYYY-MM-DD" when creating dates — avoids month confusion
  2. ✅ Always add 1 to getMonth() before displaying
  3. ✅ Always copy before mutatingnew Date(original) before calling setters
  4. ✅ Use Date.now() for performance timing — faster than new Date().getTime()
  5. ✅ Use toISOString() when sending dates to APIs — universal format
  6. Normalize time to midnight with setHours(0,0,0,0) for date-only comparisons
  7. ✅ Use toLocaleDateString(locale, options) for user-facing formatted dates
  8. ✅ For complex date operations in production, consider a library like Day.js or date-fns

What's Next?

Great work! 🎉 You now know how to work with dates confidently in JavaScript.

Next up, let's explore another powerful built-in object:

Math → — JavaScript's built-in Math object with methods for rounding, random numbers, powers, square roots, trigonometry, and more!

Let's keep going! 💪