JavaScript uses the Date object to work with dates and times.
const now = new Date();
console.log(now); // Current date and timeBehind the scenes, JavaScript stores dates as the number of milliseconds since January 1, 1970 (Unix Epoch).
You can create a Date in several ways:
const now = new Date();const birthday = new Date("2000-06-15");
const meeting = new Date("2025-04-30T10:30:00");new Date(year, monthIndex, day, hours, minutes, seconds)
const customDate = new Date(2025, 3, 30, 10, 30); // April 30, 2025 (month is 0-based)| Method | Description |
|---|---|
getFullYear() | Year (e.g., 2025) |
getMonth() | Month (0 = Jan, 11 = Dec) |
getDate() | Day of the month (1-31) |
getDay() | Day of the week (0 = Sun) |
getHours() | Hour (0–23) |
getMinutes() | Minutes (0–59)/td> |
getSeconds() | Seconds (0–59) |
getMilliseconds() | Milliseconds (0–999) |
getTime() | Milliseconds (0–999) |
const now = new Date();
console.log(now.getFullYear()); // 2025
console.log(now.getMonth()); // 3 (April)
console.log(now.getDate()); // 30
console.log(now.getDay()); // 3 (Wednesday)
console.log(now.getHours()); // e.g., 14| Method | Description |
|---|---|
getFullYear() | Year (e.g., 2025) |
setMonth() | Set the month (0–11) |
setDate() | Set the day of the month |
setHours() | Set the hours |
setMinutes() | Set the minutes |
setSeconds() | Set the seconds |
const d = new Date();
d.setFullYear(2030);
d.setMonth(0); // January
d.setDate(1);JavaScript doesn't have built-in formatting like "dd/mm/yyyy", but you can manually format:
const d = new Date();
const day = d.getDate();
const month = d.getMonth() + 1;
const year = d.getFullYear();
const formatted = `${day}/${month}/${year}`;
console.log(formatted); // e.g., 30/4/2025const d1 = new Date("2024-01-01");
const d2 = new Date("2025-01-01");
console.log(d1 < d2); // trueYou can subtract two dates to get the time in milliseconds.
const start = new Date("2025-01-01");
const end = new Date("2025-02-01");
const diffInMs = end - start;
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);
console.log(diffInDays); // 31JavaScript adjusts invalid dates automatically:
const d = new Date(2025, 0, 32); // Jan 32 → auto-corrects to Feb 1
console.log(d); // Sat Feb 01 2025| Method | Example Output |
|---|---|
toString() | "Wed Apr 30 2025 10:30:00 GMT+..." |
toDateString() | "Wed Apr 30 2025" |
toTimeString() | "10:30:00 GMT+..." |
toISOString() | "2025-04-30T10:30:00.000Z" |
get...() methods."DD-MM-YYYY" using string interpolation.