JavaScript Date Methods
JavaScript Date Methods
Section titled “JavaScript Date Methods”JavaScript’s built-in Date object provides methods to work with dates and times. These methods allow you to retrieve (get) and modify (set) various components of a date, such as the year, month, day, hour, minute, second, and millisecond.
Date Get Methods
Section titled “Date Get Methods”Get methods are used for retrieving parts of a date. Here are some of the most common:
| Method | Description |
|---|---|
getDate() | Get the day of the month as a number (1-31) |
getDay() | Get the weekday as a number (0-6, where 0 is Sunday and 6 is Saturday) |
getFullYear() | Get the year as a four-digit number (yyyy) |
getHours() | Get the hour (0-23) |
getMilliseconds() | Get the milliseconds (0-999) |
getMinutes() | Get the minutes (0-59) |
getMonth() | Get the month as a number (0-11, where 0 is January and 11 is December) |
getSeconds() | Get the seconds (0-59) |
getTime() | Get the time as the number of milliseconds since January 1, 1970, UTC (Unix Epoch) |
The getTime() Method
Section titled “The getTime() Method”getTime() returns the number of milliseconds that have elapsed since midnight on January 1, 1970, Coordinated Universal Time (UTC). This value is often called a timestamp.
const d = new Date();const timeInMs = d.getTime();console.log(timeInMs); // Example: 1678886400000 (will vary)This method is very useful for comparing dates or calculating time differences.
The getFullYear() Method
Section titled “The getFullYear() Method”getFullYear() returns the year of a date as a four-digit number:
const d = new Date(); // Defaults to the current date and timeconst year = d.getFullYear();console.log(year); // Example: 2023 (if the current year is 2023)The getDay() Method
Section titled “The getDay() Method”getDay() returns the weekday as a number (0-6):
const d = new Date(); // Example: If today is Wednesdayconst dayOfWeek = d.getDay();console.log(dayOfWeek); // Output would be 3 (since Sunday=0, Monday=1, ...)Important: In JavaScript, getDay() returns 0 for Sunday, 1 for Monday, and so on, up to 6 for Saturday. This might differ from conventions in some regions where Monday is considered the first day of the week.
You can use an array of names with getDay() to return the weekday as a name:
const d = new Date();const dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];const currentDayName = dayNames[d.getDay()];console.log(`Today is ${currentDayName}.`); // Example: "Today is Wednesday."Date Set Methods
Section titled “Date Set Methods”Set methods are used for modifying parts of a date. Here are some common ones:
| Method | Description |
|---|---|
setDate() | Set the day of the month (1-31) |
setFullYear() | Set the year (optionally, also month and day) |
setHours() | Set the hour (0-23) |
setMilliseconds() | Set the milliseconds (0-999) |
setMinutes() | Set the minutes (0-59) |
setMonth() | Set the month (0-11, where 0 is January) |
setSeconds() | Set the seconds (0-59) |
setTime() | Set the date and time using milliseconds since Epoch (January 1, 1970, UTC) |
The setFullYear() Method
Section titled “The setFullYear() Method”setFullYear() modifies the year of a date object. You can also optionally set the month and day. Remember that months are 0-indexed (January is 0).
const d = new Date(); // Creates a date object with the current date and timed.setFullYear(2025, 0, 14); // Sets year to 2025, month to January (0), day to 14console.log(d.toDateString()); // Example: "Tue Jan 14 2025"The setDate() Method
Section titled “The setDate() Method”setDate() sets the day of the month (1-31):
const d = new Date(); // Example: Current date is March 15, 2024d.setDate(20);console.log(d.toDateString()); // Output: "Wed Mar 20 2024" (if current month/year allows day 20)The setDate() method can also be used to add or subtract days from a date:
const d = new Date(); // Current dateconsole.log(`Original date: ${d.toDateString()}`);d.setDate(d.getDate() + 50); // Adds 50 days to the current dateconsole.log(`Date after 50 days: ${d.toDateString()}`);Note: If setting a day (or adding/subtracting days) results in a value outside the valid range for the current month (e.g., setting day 32 for April), the Date object will automatically adjust the month and year accordingly.
Date Input - Parsing Dates
Section titled “Date Input - Parsing Dates”JavaScript can parse date strings to create Date objects. The Date.parse() static method attempts to parse a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, or NaN if parsing fails.
const dateString = "March 21, 2012";const milliseconds = Date.parse(dateString);console.log(milliseconds); // Example: 1332288000000 (value can depend on timezone interpretation if not specified unambiguously)The Date.parse() method has limitations and its behavior with various string formats can be inconsistent across browsers. It’s generally recommended to pass date strings in the ISO 8601 format (e.g., YYYY-MM-DDTHH:mm:ss.sssZ) for reliable parsing when using Date.parse() or the Date constructor with a single string argument.
Alternatively, you can often pass a date string directly to the Date constructor:
const isoDateString = "2024-03-15T10:00:00Z"; // ISO 8601 format (UTC)const dateFromISO = new Date(isoDateString);console.log(dateFromISO.toUTCString());
// Constructing with specific components (month is 0-indexed!)const specificDate = new Date(2024, 2, 15, 12, 30, 0); // March 15, 2024, 12:30:00 local timeconsole.log(specificDate.toLocaleString());You can then use the number of milliseconds (from Date.parse() or getTime()) to create a new date object:
const millisecondsSinceEpoch = 1332288000000; // From Date.parse() or other sourceconst dateObject = new Date(millisecondsSinceEpoch);console.log(dateObject.toUTCString()); // Example: "Wed, 21 Mar 2012 00:00:00 GMT"Compare Dates
Section titled “Compare Dates”Date objects can be compared directly using comparison operators (<, >, <=, >=). However, this compares their millisecond representations. For clarity, it’s often better to explicitly compare the values from getTime().
The following example compares today’s date with January 14, 2100:
const today = new Date();const someday = new Date();someday.setFullYear(2100, 0, 14); // January 14, 2100 (month 0 is January)
let comparisonResult;if (someday.getTime() > today.getTime()) { comparisonResult = "Today is before January 14, 2100.";} else if (someday.getTime() < today.getTime()) { comparisonResult = "Today is after January 14, 2100.";} else { comparisonResult = "Today is January 14, 2100.";}console.log(comparisonResult);Reminder: When working with months in JavaScript Date objects (e.g., in the Date constructor or with setMonth()/getMonth()), January is represented as 0 and December as 11. This is a common source of off-by-one errors.
Complete JavaScript Date Reference
Section titled “Complete JavaScript Date Reference”For a comprehensive and up-to-date reference on all Date object properties and methods, consult the MDN Web Docs for JavaScript Dates. (Example: Search for ‘MDN Date JavaScript’).
This resource provides detailed descriptions, syntax, and examples for all Date-related features.