Js Dates in JavaScript
? JavaScript Dates
What is the JavaScript Date Object?
Used to work with dates and times.
Represents a single point in time (down to milliseconds).
Based on the number of milliseconds since January 1, 1970 UTC (Unix Epoch).
Creating Dates
const now = new Date(); // Current date/timeconst specificDate = new Date('2025-06-02'); // Specific date stringconst fromParts = new Date(2025, 5, 2); // Year, month (0-based), dayNote: Months are zero-indexed (0 = January, 5 = June).
Common Date Methods
| Method | Description |
|---|---|
.getFullYear() | Get year (e.g., 2025) |
.getMonth() | Get month (0-11) |
.getDate() | Get day of month (1-31) |
.getDay() | Get day of week (0 = Sunday) |
.getHours() | Get hour (0-23) |
.getMinutes() | Get minutes (0-59) |
.getSeconds() | Get seconds (0-59) |
.getMilliseconds() | Get milliseconds (0-999) |
.getTime() | Get timestamp in milliseconds |
.toISOString() | Get ISO 8601 date string |
.toLocaleDateString() | Get date in locale format |
Example Usage
const date = new Date();console.log(date.getFullYear()); // 2025console.log(date.getMonth()); // 5 (June)console.log(date.getDate()); // 2console.log(date.toISOString()); // "2025-06-02T...Z"Modifying Dates
Use set methods to change parts of the date:
date.setFullYear(2030);date.setMonth(0); // Januarydate.setDate(15);Comparing Dates
const d1 = new Date('2025-06-02');const d2 = new Date('2025-06-15');console.log(d1 < d2); // trueconsole.log(d1.getTime() === d2.getTime()); // falseTips
Use ISO 8601 format for date strings to avoid cross-browser issues.
For advanced date/time handling, consider libraries like date-fns or Luxon.
Want a demo on formatting dates, parsing strings, or time zones?