Creating Date objects
Learn to create Date objects and basic methods like now and parse.
Creating Date objects
A Date object represents a moment in time. Calling new Date() gives the current date and time. You can also build a date from its components.
const now = new Date();
const birthday = new Date(1995, 8, 27);Here 8 means September, because the month index starts at zero: January is 0, September is 8. The second argument is the month and the third is the day. This lets you pin a specific date exactly.
Date.now and Date.parse
Date.now() returns the current timestamp: the number of milliseconds since 1 January 1970. This value is known as the epoch.
const ts = Date.now();
console.log(ts); // e.g. 1705276800000It is a large number that grows on every call. Date.parse('2024-01-15') converts a date string into a timestamp. Timestamps are very handy for comparing two dates.
Exercise Create the date 15 January 2024 and log its year
Assign the date 15 January 2024 to startDate using new Date(2024, 0, 15). Then read its year with getFullYear() and log it with console.log.
Show example solution
new Date takes the year, month and day; the month starts at zero. getFullYear returns the four-digit year.
Example solution:
let startDate = new Date(2024, 0, 15);
console.log(startDate.getFullYear());
Test yourself
-
Which returns a Date object with the current date and time?
- new Date(2024)
- Date.now()
- new Date()
- new Time()
Show answer
new Date() — Correct! new Date() returns an object with the current date and time.
-
Get the timestamp with Date.now
const now = ____; console.log(now);Show answer
const now = Date.now(); console.log(now); -
Match the Date constructor forms
- new Date()
- current date
- new Date(2024, 0, 15)
- specific date
- new Date(1705276800000)
- from timestamp
- Date.now()
- ms timestamp