Reading date components
Learn to read date components with getFullYear, getMonth and getDate.
Reading date components
You read the parts of a Date object with methods that start with get. Each method returns a number.
const d = new Date(2024, 4, 12);
d.getFullYear(); // 2024
d.getMonth(); // 4 (May)
d.getDate(); // 12
d.getDay(); // 1 (Monday)getMonth returns the month from 0 to 11; May is 4. getDate returns the day of the month from 1 to 31. getDay returns the weekday from 0 to 6; 0 is Sunday.
Reading hours and minutes
You can also read time parts like hours and minutes. The same get family applies.
const t = new Date();
t.getHours(); // 0-23
t.getMinutes(); // 0-59
t.getSeconds(); // 0-59getHours returns the hour in 24-hour format. Minutes and seconds range from 0 to 59. With these values you build a clock or a time stamp.
Exercise Log the month and day values
The event variable holds the date 12 May 2024. Read the month with getMonth() and the day with getDate(), and log both with console.log.
Show example solution
getMonth returns the month 0-11; getDate returns the day of the month 1-31.
Example solution:
const event = new Date(2024, 4, 12);
console.log(event.getMonth());
console.log(event.getDate());
Test yourself
-
Which month is created by new Date(2024, 3, 10)?
new Date(2024, 3, 10)- April (4th month)
- March (3rd month)
- May (5th month)
- January (1st month)
Show answer
April (4th month) — Correct! The month index starts at zero, so 3 gives April.
-
Read the month value
const d = new Date(2024, 2, 15); const month = d.____; console.log(month);Show answer
const d = new Date(2024, 2, 15); const month = d.getMonth(); console.log(month); -
Match the get methods
- getFullYear()
- year
- getMonth()
- month (0-11)
- getDate()
- day (1-31)
- getDay()
- weekday