Date set methods allow you to change the value of an existing Date object. You can set specific components like the year, month, day, or even milliseconds.
| Method | Description |
|---|---|
setFullYear() |
Sets the year (optionally month and day) |
setMonth() |
Sets the month (0-11) |
setDate() |
Sets the day of the month (1-31) |
setHours() |
Sets the hour (0-23) |
setTime() |
Sets the time (ms since Jan 1, 1970) |
You can easily add days to a date by combining setDate() and
getDate(). JavaScript will automatically handle the overflow into new months
or years.
const d = new Date();
// Add 50 days to the current date
d.setDate(d.getDate() + 50);
Dates can be compared using comparison operators (>, <,
>=, <=). This works because JavaScript converts the dates into
their numeric millisecond values for the comparison.
let today = new Date();
let someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
== or
=== will not work to compare if two dates are the same
moment. You must compare their getTime() values instead.
setFullYear() can also take month and day as optional
parametersgetTime() for identical equality
checks