JavaScript ยท Chapter 24 of 55
JavaScript Dates
The `Date` object represents a single moment in time, used for tasks like timestamps, scheduling, and formatting dates for display.
You create a Date with `new Date()`, which defaults to the current moment, or pass specific values to construct a particular date.
Creating dates
`new Date()` gives now. `new Date(2024, 0, 15)` creates January 15, 2024 โ note that months are zero-indexed (0 = January).
Getting date parts
Methods like `getFullYear()`, `getMonth()`, `getDate()`, and `getDay()` extract specific components from a Date object.
Example 1 (javascript)
let d = new Date(2024, 0, 15);
console.log(d.getFullYear());
console.log(d.getMonth());Output
2024
0getMonth() returns 0 for January due to zero-indexing.
Example 2 (javascript)
let now = new Date();
console.log(typeof now.getTime());Output
numbergetTime() returns milliseconds since Jan 1, 1970 (the Unix epoch).
Key points
- `new Date()` creates a date object for the current moment.
- Months are zero-indexed: January is 0, December is 11.
- getFullYear(), getMonth(), getDate() extract date parts.
- getTime() returns milliseconds since the Unix epoch.
๐ก Note: For robust date formatting and manipulation in real apps, many developers use a library like date-fns or Day.js.
