JavaScript : Set Date Methods

In JavaScript, the Date object provides methods for setting various components of a date and time. These methods allow you to modify the year, month, day, hour, minute, second, and millisecond of a Date object. Here are the commonly used methods to set date components:

1. setFullYear()


Sets the year (four digits) of the specified date according to local time.


let date = new Date();
date.setFullYear(2023);
console.log(date.getFullYear()); // Example output: 2023

 

2. setMonth()


Sets the month (0-11) of the specified date according to local time.


let date = new Date();
date.setMonth(11); // December (Note: January is 0, February is 1, ..., December is 11)
console.log(date.getMonth()); // Example output: 11

 

3. setDate()


Sets the day of the month (1-31) for the specified date according to local time.


let date = new Date();
date.setDate(25);
console.log(date.getDate()); // Example output: 25

 

4. setHours()


Sets the hour (0-23) of the specified date according to local time.


let date = new Date();
date.setHours(14);
console.log(date.getHours()); // Example output: 14

 

5. setMinutes()


Sets the minutes (0-59) of the specified date according to local time.


let date = new Date();
date.setMinutes(30);
console.log(date.getMinutes()); // Example output: 30

 

6. setSeconds()


Sets the seconds (0-59) of the specified date according to local time.


let date = new Date();
date.setSeconds(45);
console.log(date.getSeconds()); // Example output: 45

 

7. setMilliseconds()


Sets the milliseconds (0-999) of the specified date according to local time.


let date = new Date();
date.setMilliseconds(123);
console.log(date.getMilliseconds()); // Example output: 123

 

8. setTime()


Sets the milliseconds since January 1, 1970, 00:00:00 UTC, for the specified date according to local time.


let date = new Date();
date.setTime(1640995200000); // January 1, 2022 00:00:00 UTC
console.log(date); // Example output: Sat Jan 01 2022 05:30:00 GMT+0530 (India Standard Time)

 

These methods provide a convenient way to modify various components of a date and time in a Date object in JavaScript, allowing you to perform date-related operations and manipulate dates in your applications.