Javascript Date setHours(hours)

Introduction

Javascript Date setHours (hours) sets the date's hours.

Setting the hours to a number greater than 23 also increments the day of the month.

dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])

Parameters

  • hoursValue - an integer between 0 and 23, representing the hour. If a value greater than 23 is provided, the date time will be incremented by the extra hours.
  • minutesValue - Optional. an integer between 0 and 59, representing the minutes. If a value greater than 59 is provided, the date time will be incremented by the extra minutes.
  • secondsValue - Optional. an integer between 0 and 59, representing the seconds. If a value greater than 59 is provided, the date time will be incremented by the extra seconds. If you specify the secondsValue parameter, you must also specify the minutesValue.
  • msValue - Optional. a number between 0 and 999, representing the milliseconds. If a value greater than 999 is provided, the date time will be incremented by the extra milliseconds. If you specify the msValue parameter, you must also specify the minutesValue and secondsValue.

Return value

The number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date.

If a parameter is outside of the expected range, setHours() will update the date accordingly.

let today = new Date();
console.log(today);//w ww  . j ava  2 s.c om
today.setHours(0);
console.log(today); // still today, but the hour is changed to 0
today.setHours(20);
console.log(today); 

today.setHours(0, 0, 0, 0);
console.log(today); // still today, now 00:00:00 sharp.

Set the time to 15:35:01

var d = new Date();
d.setHours(15, 35, 1);/* ww  w.jav  a2s  . c o m*/
console.log(d);

Set the time to 48 hours ago:

var d = new Date();
d.setHours(d.getHours() - 48);/*from  ww  w  .j  a  va  2s  . c  o m*/
console.log(d);



PreviousNext

Related