In JavaScript, the Date
object also provides methods to set various components of a date. Here are some commonly used set methods:
setDate(): Sets the day of the month (1-31) for a specified date object.
let today = new Date();
today.setDate(15); // Sets the day of the month to the 15th
setMonth(): Sets the month (0-11) for a specified date object.
let today = new Date();
today.setMonth(5); // Sets the month to June (remember, January is 0)
setFullYear(): Sets the year (4 digits) for a specified date object.
let today = new Date();
today.setFullYear(2023); // Sets the year to 2023
setHours(): Sets the hour (0-23) for a specified date object.
let now = new Date();
now.setHours(10); // Sets the hour to 10:00 AM
setMinutes(): Sets the minutes (0-59) for a specified date object.
let now = new Date();
now.setMinutes(30); // Sets the minutes to 30
setSeconds(): Sets the seconds (0-59) for a specified date object.
let now = new Date();
now.setSeconds(45); // Sets the seconds to 45
setMilliseconds(): Sets the milliseconds (0-999) for a specified date object.
let now = new Date();
now.setMilliseconds(500); // Sets the milliseconds to 500
setTime(): Sets the number of milliseconds since January 1, 1970 (UNIX Epoch) for a specified date object.
let now = new Date();
now.setTime(1652904000000); // Sets the date to June 20, 2022
These methods allow you to modify specific components of a date or time in a Date
object in JavaScript, enabling you to perform various operations and manipulations with dates and times.