JavaScript setHours function is a Date Function useful 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 the JavaScript 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> JS </title> </head> <body> <h1> JExample </h1> <script> var dt = Date(); document.write("Date and Time : " + dt + "<br/>"); dt.setHours(22); document.write("After : " + dt); </script> </body> </html>
Example
Date and Time: Mon Nov 05 2018 12:02:24 GMT+0530 (Indian Standard Time)
After : Mon Nov 05 2018 22:02:24 GMT+0530 (Indian Standard Time)
setHours Example 2
In this JavaScript set hours example, we set the hours of a custom date to 02 AM.
<!DOCTYPE html> <html> <head> <title> JS </title> </head> <body> <h1> JavaScriptsetHoursFunctionExample </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>
In this set Hours example, we set the Hours to 22, Minutes to 34, and Seconds to 12
<!DOCTYPE html> <html> <head> <title> JS </title> </head> <body> <h1> 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 : " + dt); </script> </body> </html>
Example
Date and Time: Tue Nov 06 2018 09:12:57 GMT+0530 (Indian Standard Time)
After : Tue Nov 06 2018 22:34:12 GMT+0530 (Indian Standard Time)