Javascript - Date setUTCHours() Method

The setUTCHours() method sets the hour of a date object, according to the UTC time.

Description

The setUTCHours() method sets the hour of a date object, according to the UTC time.

You can use this method to set the minutes, seconds and milliseconds.

UTC time is the same as GMT time.

Syntax

Date.setUTCHours(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 the 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 the 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, according to UTC time:

Demo

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

//Set the time to 15:35:01 UTC time
//display a date after changing the hours, minutes, and seconds.
var d = new Date();
d.setUTCHours(15, 35, 1);
console.log(d);

//Set the time to 48 hours ago, using UTC methods:

//display a date after changing it to 48 hours ago.
var d = new Date();
d.setUTCHours(d.getUTCHours() - 48);
console.log(d);

Result