Date.prototype.setMonth
Sets the month for a specified date according to local time
Syntax
date.setMonth(monthValue, dayValue?)Parameters
| Parameter | Type | Description |
|---|---|---|
| monthValue | number | A zero-based integer (0-11) |
| dayValue | number | Optional day of the month |
Return Value
The number of milliseconds from epoch for the updated date
Examples
const date = new Date('2024-06-15');
date.setMonth(0); // January
console.log(date.getMonth()); // 0function addMonths(date: Date, months: number) {
const d = new Date(date);
d.setMonth(d.getMonth() + months);
return d;
}const date = new Date('2024-01-31');
date.setMonth(1); // Feb - note: may overflow
console.log(date.getDate()); // Could be March 2Understanding Date.prototype.setMonth
The Date.prototype.setMonth method in JavaScript sets the month for a specified date according to local time. It belongs to the Date object and is one of the most widely used methods for working with date values in modern JavaScript and TypeScript applications.
The method signature is date.setMonth(monthValue, dayValue?). It accepts 2 parameters: monthValue, dayValue. When called, it returns the number of milliseconds from epoch for the updated date. Understanding when and how to use setMonth() helps you write more expressive, readable code.
Common use cases for Date.prototype.setMonth include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like date-getmonth, date-setfullyear, date-setdate, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Date.prototype.setMonth is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Date.prototype.getMonthReturns the month (0-11) for the specified date according to local time
Date.prototype.setFullYearSets the full year for a specified date according to local time and returns the updated timestamp
Date.prototype.setDateSets the day of the month for a specified date according to local time
More Date Methods
Other methods in the Date object
Related Tools
More Date Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.