JavaScript Set Date Methods
JavaScript provides several built-in methods to set date values.
In this tutorial we will explore them one by one.
Let's get started.
The dateObject.setFullYear(year[, month[, day]])
Method
This method sets the full year of a date object according to local time.
If the month or day are not specified, they are set to the current month or day.
As an example:
const date = new Date("2023-03-31T13:59:00");
date.setFullYear(2024);
console.log(date); // Output: Fri Mar 31 2024 13:59:00 GMT-0700 (Pacific Daylight Time)
The dateObject.setMonth(month[, day])
Method
This method sets the month of a date object according to local time. If the day is not specified, it is set to the current day.
As an example:
const date = new Date("2023-03-31T13:59:00");
date.setMonth(4);
console.log(date); // Output: Sat May 31 2023 13:59:00 GMT-0700 (Pacific Daylight Time)
The dateObject.setDate(day)
Method
This method sets the day of the month of a date object according to local time.
As an example:
const date = new Date("2023-03-31T13:59:00");
date.setDate(15);
console.log(date); // Output: Wed Mar 15 2023 13:59:00 GMT-0700 (Pacific Daylight Time)
The dateObject.setHours(hour[, min[, sec[, ms]]])
Method
This method sets the hour, minute, second, and millisecond of a date object according to local time.
As an example:
const date = new Date("2023-03-31T13:59:00");
date.setHours(18, 30, 0, 0);
console.log(date); // Output: Fri Mar 31 2023 18:30:00 GMT-0700 (Pacific Daylight Time)
The dateObject.setMinutes(min[, sec[, ms]])
Method
This method sets the minute, second, and millisecond of a date object according to local time.
As an example:
const date = new Date("2023-03-31T13:59:00");
date.setMinutes(30, 0, 0);
console.log(date); // Output: Fri Mar 31 2023 13:30:00 GMT-0700 (Pacific Daylight Time)