JavaScript Dates
What is a Date in JavaScript?
JavaScript uses the Date
object to work with dates and times.
const now = new Date();
console.log(now); // Current date and time
Behind the scenes, JavaScript stores dates as the number of milliseconds since January 1, 1970 (Unix Epoch).
Creating Date Objects
You can create a Date
in several ways:
1. Current Date and Time
const now = new Date();
2. Specific Date and Time
const birthday = new Date("2000-06-15");
const meeting = new Date("2025-04-30T10:30:00");
3. Using Individual Values
new Date(year, monthIndex, day, hours, minutes, seconds)
const customDate = new Date(2025, 3, 30, 10, 30); // April 30, 2025 (month is 0-based)
Getting Date Components
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> </tr> |
getSeconds() |
Seconds (0–59) |
getMilliseconds() |
Milliseconds (0–999) |
getTime() |
Milliseconds (0–999) |
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);
Formatting Dates
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/2025
Date Comparison
const d1 = new Date("2024-01-01");
const d2 = new Date("2025-01-01");
console.log(d1 < d2); // true
Calculating Time Differences
You 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); // 31
Auto-Correction
JavaScript 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
Converting to String
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" |
🧪 Practice Exercise:
Task:
- Create a new date for your birthday.
- Print the current year, month, and date using
get...()
methods. - Calculate how many days are left until New Year.
- Compare two dates to check which comes first.
- Format today’s date as
"DD-MM-YYYY"
using string interpolation.