JS Set Date

JavaScript Set Date Methods: Modifying Dates

In the previous section, we learned how to get information out of a Date object. But what if you need to change a date? What if you want to calculate a date 30 days in the future, or set the year to 2050?

JavaScript provides Set Date Methods to let you safely modify parts of a Date object (like the year, month, day, hour, etc.).


The Core "Set" Methods

Here is a quick reference table of the most commonly used methods for setting information in a date object:

Method Description
setFullYear() Set the year (optionally month and day)
setMonth() Set the month (0 to 11)
setDate() Set the day of the month (1 to 31)
setHours() Set the hour (0 to 23)
setMinutes() Set the minutes (0 to 59)
setSeconds() Set the seconds (0 to 59)
setMilliseconds() Set the milliseconds (0 to 999)
setTime() Set the time (in milliseconds since Jan 1, 1970)

Setting the Year, Month, and Day

The setFullYear() method allows you to change the year of an existing date object.

setFullYear() Example

const d = new Date();

// Change the year to 2050 d.setFullYear(2050);

console.log(d);

Setting Multiple Values at Once

The setFullYear() method can optionally take the month and day as secondary arguments, allowing you to set three values in a single line of code!

Reminder: Just like the get methods, months are 0-indexed when setting them! (0 = January, 11 = December).

Setting Year, Month, and Day

const d = new Date();

// Set date to November 3rd, 2025 // (Year: 2025, Month: 10 for Nov, Day: 3) d.setFullYear(2025, 10, 3);

console.log(d);


The Magic of Date Auto-Correction

One of the best features of the Date object in JavaScript is that it automatically corrects itself if you provide out-of-range values.

For example, what happens if you try to set the date to the 35th of January? Since January only has 31 days, JavaScript will automatically roll over the extra 4 days into February!

Date Auto-Correction Example

// Create a date for January 1st, 2024
const d = new Date("2024-01-01");

// Try to set the day to the 35th d.setDate(35);

// The date automatically rolls over to February 4th! console.log(d);


Calculating Future or Past Dates

The auto-correction feature makes it incredibly easy to add or subtract days from a given date.

To add 50 days to the current date, you simply get the current day (getDate()), add 50 to it, and pass that back into setDate(). JavaScript handles all the messy math of figuring out leap years and different month lengths!

Adding Days to a Date

const d = new Date();

// Add 50 days to the current date d.setDate(d.getDate() + 50);

console.log("50 days from now will be: " + d);

You can use the exact same technique to subtract days (e.g., d.setDate(d.getDate() - 10) to go 10 days into the past).


Exercise

?

If d is a Date object representing August 30th, what happens if you execute d.setDate(d.getDate() + 5)?