Javascript - Date setHours() Method

The setHours() method sets the hour of a date object.

Description

The setHours() method sets the hour of a date object.

This method can also be used to set the minutes, seconds and milliseconds.

Syntax

Date.setHours(hour, min, sec, millisec)

Parameter Values

Parameter Require Description
hour Required.An integer representing the hour.
min Optional.An integer representing the minutes.
sec Optional.An integer representing the seconds
millisec Optional.An integer representing the milliseconds

For hour value, the expected values are 0-23, but other values are allowed:

  • -1 will result in the last hour of the previous day 24 will result in the first hour of the next day

For minute value, the expected values are 0-59, but other values are allowed:

  • -1 will result in the last minute of the previous hour
  • 60 will result in the first minute of the next hour

For the second value, the expected values are 0-59, but other values are allowed:

  • -1 will result in the last second of the previous minute
  • 60 will result in the first second of the next minute

For the millisec value, the expected values are 0-999, but other values are allowed:

  • -1 will result in the last millisecond of the previous second
  • 1000 will result in the first millisecond of the next second

Return

A Number, representing the number of milliseconds between the date object and midnight January 1 1970

Example

Set the hour to 15:

Demo

//display a date after changing the hours.
var d = new Date();
d.setHours(15);/*from w  w  w  .  java 2  s  . c om*/
console.log(d);

//Set the time to 15:35:01
//display a date after changing the hours, minutes, and seconds.
d.setHours(15, 35, 1);
console.log(d);

//Set the time to 48 hours ago:
d.setHours(d.getHours() - 48);
console.log(d);

Result