JavaScript setHours()Method

Date 对象参考手册JavaScript Date Object

Example

Set the time field to 15:

var d = new Date();
d.setHours(15);

dOutput:


Try it Yourself »

Definition and Usage

The setHours() method is used to set the hour field of a specified time.

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


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the setHours() method.


Syntax

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

Parameter Values

Parameter Description
hour Required.

A number representing the hour, between 0 (midnight) and 23 (11 pm), in local time (same below).

  • -1 is the last hour of yesterday
  • 24 is the first hour of tomorrow
min Optional. A number representing the minutes.

Between 0 and 59. This parameter is not supported before ECMAScript standardization:

  • -1 is the last minute of the previous hour
  • 60 is the first minute of the next hour
sec Optional. A number representing the seconds.

Between 0 and 59. This parameter is not supported before ECMAScript standardization:

  • -1 is the last second of the previous minute
  • 60 is the first second of the next minute
millisec Optional. A number representing the milliseconds.

Between 0 and 999. This parameter is not supported before ECMAScript standardization:

  • -1 is the last millisecond of the previous second
  • 1000 is the first millisecond of the next second

Return Value

Type Description
Number Milliseconds between the date object and midnight January 1 1970

Technical Details

JavaScript Version: 1.0


More Examples

Example

In this example, we will set the time to 15:35:01 using the setHours() method:

var d = new Date();
d.setHours(15,35,1);

dOutput:


Try it Yourself »

Example

Set the time to 48 hours ago:

var d = new Date();
d.setHours(d.getHours()-48);

dOutput:


Try it Yourself »


Date 对象参考手册JavaScript Date Object

Other Extensions