What is setHours() in JavaScript?
The setHours function in JS is a method of the Date class with the following syntax:
setHours(hoursValue)
setHours(hoursValue, minutesValue)
setHours(hoursValue, minutesValue, secondsValue)
setHours(hoursValue, minutesValue, secondsValue, msValue)
Parameters
hoursValueis an integer value from0to23(representing time in 24-hour clock format). A value greater than23is added as extra hours to the date object.minutesValueis an integer value from0to59that represents minutes. A value greater than59is added as extra minutes to the date object.secondsValueis an integer value from0to59that represents seconds. A value greater than59is added as extra seconds to the date object.msValueis an integer value from0to999that represents milliseconds. A value greater than999is added as extra milliseconds to the date object.
Note: Only the
hoursValueparameter is required, the rest are optional.
Return value
setHoursreturns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC till the updated time.
The setHours function is called on a Date object, which results in the specified parameters being changed in the Date object.
Example
The following code demonstrates the usage of the setHours function:
let d1 = new Date('June 29, 2021 15:39:05:32');let d2 = new Date('June 29, 2021 15:39:05:32');let d3 = new Date('June 29, 2021 15:39:05:32');let d4 = new Date('June 29, 2021 15:39:05:32');console.log('Dates Before Changing:');console.log('d1: ', d1);console.log('d2: ', d2);console.log('d3: ', d3);console.log('d4: ', d4);d1.setHours(8);d2.setHours(8, 8);d3.setHours(8, 8, 8);d4.setHours(8, 8, 8, 8);console.log('Dates After Changing:');console.log('d1: ', d1);console.log('d2: ', d2);console.log('d3: ', d3);console.log('d4: ', d4);
In the example above, the variables d1, d2, d3, and d4 are Date objects that have the same date, June 29, 2021 15:39:05:32, initially. The setHours function is applied on all of them to make the hours, minutes, seconds, and milliseconds to the value 8. For d1, only the hours is set to 8. For d2, both hours and minutes are set to 8. For d3, hours, minutes, and seconds are set to 8. Finally, for d4, hours, minutes, seconds, and milliseconds are set to 8.
Free Resources