Course contentsShow
← JavaScript
Lesson 1625 of 2,72335. Standard Library and Built-insFree lesson

Setting Date Components with Setters

Modify Date objects using setFullYear, setMonth, setDate and related methods, understanding mutation.

Setting Date Components with Setters

You'll learn how to modify existing Date objects using setter methods, understanding that these changes mutate the original object.

The Core Idea

While getter methods like getFullYear() and getMonth() let you read parts of a date, setter methods let you change them. These setters modify the Date object in place — they don't create a new date, they update the existing one. Think of a Date object like a digital clock: getters let you check the time, setters let you adjust it.

Common Setter Methods

Just as there are getters for each date component, there are corresponding setters:

const myDate = new Date('2024-03-15T10:30:00');

// Change individual components
myDate.setFullYear(2025);  // Year → 2025
myDate.setMonth(11);       // Month → December (0-indexed!)
myDate.setDate(25);        // Day → 25th

console.log(myDate);  // 2025-12-25T10:30:00

For time components:

const eventTime = new Date('2024-06-01T14:30:00');

eventTime.setHours(16);
eventTime.setMinutes(45);
eventTime.setSeconds(30);

console.log(eventTime);  // 2024-06-01T16:45:30

Understanding Mutation

Critical point: Setters mutate the original object. They don't return a new Date:

const original = new Date('2024-01-01');
const result = original.setMonth(5);  // returns timestamp (milliseconds)

console.log(original);  // 2024-06-01 (original is modified!)
console.log(result);    // A number (timestamp), not a Date object

UTC Setters

Like getters, setters have UTC versions: setUTCFullYear(), setUTCMonth(), setUTCDate(), etc., which modify the date in UTC time rather than local time.

Key Takeaway: Date setter methods (setFullYear, setMonth, setDate, setHours, etc.) mutate the original Date object in place and return a timestamp, not a new Date — use them when you need to modify existing dates rather than create new ones.