Date and Time
JavaScript provides the Date object to work with dates and times. It is based on a time value that is the number of milliseconds since 1 January 1970 UTC (the Unix Epoch).
1. Creating Dates
There are four ways to create a new Date object:
// 1. Current date and time
const now = new Date();
// 2. From a specific date string
const dateStr = new Date("2023-12-25");
// 3. From milliseconds (since Epoch)
const dateMs = new Date(1703462400000);
// 4. From components (Year, Month, Day, Hour, Minute, Second, Ms)
// Note: Month is 0-indexed (0 = January, 11 = December)
const dateComp = new Date(2023, 11, 25, 10, 30, 0);
2. Getting Date Components
You can extract specific parts of the date using various methods. Note that most return local time values.
const d = new Date("2023-12-25T10:30:00");
console.log(d.getFullYear()); // 2023
console.log(d.getMonth()); // 11 (December)
console.log(d.getDate()); // 25 (Day of month)
console.log(d.getDay()); // 1 (Day of week, 0 = Sunday)
console.log(d.getHours()); // 10
console.log(d.getTime()); // 1703500200000 (Timestamp in ms)
To get UTC values, use methods like getUTCFullYear(), getUTCHours(), etc.
3. Setting Date Components
You can modify an existing date object.
const d = new Date();
d.setFullYear(2024);
d.setMonth(0); // January
4. Formatting Dates
JavaScript's native formatting capabilities have improved with Intl.DateTimeFormat, but basic methods exist too.
const d = new Date();
console.log(d.toDateString()); // "Mon Dec 25 2023"
console.log(d.toISOString()); // "2023-12-25T10:30:00.000Z" (ISO 8601)
console.log(d.toLocaleDateString()); // "12/25/2023" (Locale dependent)
console.log(d.toLocaleString()); // "12/25/2023, 10:30:00 AM"
5. Timestamps and Performance
To measure how long code takes to run, use Date.now().
const start = Date.now();
// ... do something ...
const end = Date.now();
console.log(`Execution time: ${end - start} ms`);
6. Libraries
The native Date object can be clunky and mutable. For complex date manipulation, libraries are often used:
- date-fns: Modern, modular, immutable.
- Day.js: Lightweight, API similar to Moment.js.
- Moment.js: Legacy (maintenance mode), heavy, mutable. Avoid for new projects.
- Temporal API: A future native API proposal to fix
Dateissues.