Computer >> Computer tutorials >  >> Programming >> Javascript

Date.setUTCHours() function in JavaScript


The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

The setUTCHours() function of the date object accepts an integer representing the hours and replaces the value of the hours in the current date (time) with it, according to the universal time.

Syntax

Its Syntax is as follows

dateObj.setUTCHours();

Example

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('september 26, 89 12:4:25:96');
      document.write("Current date: "+dateObj.toUTCString());
      document.write("<br>");
      dateObj.setUTCHours(23);
      document.write(" Date after setting the hours: "+dateObj.toUTCString());
      document.write();
   </script>
</body>
</html>

Output

Current date: Tue, 26 Sep 1989 06:34:25 GMT
Date after setting the hours: Tue, 26 Sep 1989 23:34:25 GMT

Example

Though you do not mention the hours of the day while creating the date object, You can still set it using the setHours() function according to the universal time.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('26, September, 1989 4:25:96');
      dateObj.setHours(5);
      document.write(dateObj.toString());
   </script>
</body>
</html>

Output

Tue Sep 26 1989 05:25:00 GMT+0530 (India Standard Time)

Example

In the same way, though you do not pass any value to the constructor while creating the date object still you can set the hours using this function according to the universal time and the month, date, year and, other values remain same as in the current date (and time).

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date();
      dateObj.setHours(5);
      document.write(dateObj.toString());
   </script>
</body>
</html>

Output

Thu Oct 18 2018