JavaScript setHours Function

JavaScript setHours function is a Date Function, used to set the Hours, Minutes, and Seconds of a given date as per local time. The syntax of the setHours function is:

 Date.setHours(Hours_Value, Minutes, Seconds, Milliseconds)

In setHours function, Minutes, Seconds, and Milliseconds arguments are optional.

JavaScript setHours Function Example

We used the setHours function to set the current time to 22 hours.

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript Set Hours Functions </title>
</head>
<body>
    <h1> JavaScript setHours Function Example </h1>
<script>
  var dt = Date();  
  document.write("Date and Time : " + dt + "<br/>");

  dt.setHours(22);
  document.write("After setHours() : " + dt);
</script>
</body>
</html>
JavaScript setHours Function Example

Date and Time: Mon Nov 05 2018 12:02:24 GMT+0530 (Indian Standard Time)
After setHours(): Mon Nov 05 2018 22:02:24 GMT+0530 (Indian Standard Time)

JavaScript set Hours Example 2

In this JavaScript set hours example, we set the hours of a custom date to 02 AM

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript Set Hours Functions </title>
</head>
<body>
    <h1> JavaScript setHours Function Example </h1>
<script>
  var dt = Date("April 1, 2017 19:11:22");
  document.write("Date and Time : " + dt + "<br/>");

  dt.setHours(02);
  document.write("After setHours() : " + dt);
</script>
</body>
</html>
JavaScript setHours Function 2

In this setHours example, we set the Hours to 22, Minutes to 34, and Seconds to 12

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript Set Hours Functions </title>
</head>
<body>
    <h1> JavaScript setHours Function Example </h1>
<script>
  var dt = Date("April 1, 2017 19:11:22");
  document.write("Date and Time : " + dt + "<br/>");

  dt.setHours(22, 34, 12);
  document.write("After setHours() : " + dt);
</script>
</body>
</html>
JavaScript setHours Function Example

Date and Time: Tue Nov 06 2018 09:12:57 GMT+0530 (Indian Standard Time)
After setHours(): Tue Nov 06 2018 22:34:12 GMT+0530 (Indian Standard Time)