Date Object
Overview
The Date object in JavaScript is used to work with dates and times. Under the hood, a Date object contains a number representing the milliseconds since the 'Unix Epoch' (January 1, 1970, UTC).
Working with Dates in vanilla JS is notoriously difficult due to zero-indexed months, timezone quirks, and formatting challenges. However, knowing the native Date API is essential for interviews.
Syntax
// Current Date and Time
const now = new Date();
// Passing a specific date string (ISO format preferred)
const specificDate = new Date("2026-09-15T12:00:00Z");
// Passing numbers: new Date(year, monthIndex, day, hours, minutes, seconds)
// Note: Month is 0-indexed! (0 = Jan, 8 = Sept)
const createdDate = new Date(2026, 8, 15, 12, 0, 0);const date = new Date();
console.log(date.getFullYear()); // e.g., 2026
console.log(date.getMonth()); // 0-11
console.log(date.getDate()); // 1-31 (Day of the month)
console.log(date.getDay()); // 0-6 (Day of the week, 0 is Sunday)const d = new Date();
// Standard for databases
console.log(d.toISOString()); // "2026-09-15T10:30:00.000Z"
// Human readable localized string
console.log(d.toLocaleDateString('en-US')); // "9/15/2026"Common Pitfalls
Months are zero-indexed! January is
0, December is11. This trips up nearly every developer. However, the days of the month (getDate()) start at1.Never trust the user's local system time for critical timestamps (like payment logs); always rely on your backend server time.
Interview Questions
How do you get a Unix Timestamp (milliseconds since 1970) in JavaScript without creating a new Date object?
You can use the static method Date.now(). It is faster and more memory efficient than new Date().getTime().
What is the difference between getDate() and getDay()?
getDate() returns the day of the month (1-31). getDay() returns the day of the week (0-6, where 0 is Sunday).
Real-World Example
Calculating how many days ago a post was created.
const created = new Date("2026-09-10");
const now = new Date();
// Get difference in milliseconds
const diffTime = Math.abs(now - created);
// Convert to days
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));Check Your Knowledge
Test your understanding of Date Object with these quick questions.