• JavaScript Video Tutorials

JavaScript Date getHours() Method



The JavaScript Date.getHours() method is used to retrieve the hour value of a date object according to the local time. The return value will be an integer between 0 and 23 representing the hour according to the local time zone.

If the Date object is created with no arguments, it returns the current hour in the local time zone. If the Date object is created with a specific date and time, it returns the hour component of that date in the local time zone. If the Date object is invalid, it returns NaN (Not-a-Number).

Syntax

Following is the syntax of JavaScript Date getHours() method −

getHours();

This method does not accept any parameters.

Return Value

This method returns an integer representing the hour component of the given date object, ranging from 0 to 23.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript Date getHours() method −

<html>
<body>
<script>
   const currentDate = new Date();
   const currentHour = currentDate.getHours();

   document.write("Current Hour:", currentHour);
</script>
</body>
</html>

Output

The above program returns the current hour according to the local time.

Example 2

In this example, we are retrieving the hour from the specific date and time.

<html>
<body>
<script>
   const customDate = new Date('2023-01-25T15:30:00');
   const Hour = customDate.getHours();

   document.write("Hour:", Hour);
</script>
</body>
</html>

Output

The above programs returns integer 15 as hour.

Example 3

According to the current local time, the program will return a greeting based on whether it is morning, afternoon, or evening.

<html>
<body>
<script>
   function getTimeOfDay() {
      const currentHour = new Date().getHours();

      if (currentHour >= 6 && currentHour < 12) {
         return "Good morning...";
      } else if (currentHour >= 12 && currentHour < 18) {
         return "Good afternoon...";
      } else {
         return "Good evening...";
      }
   }

   const greeting = getTimeOfDay();

   document.write(greeting);
</script>
</body>
</html>

Output

As we can see the output, respective greeting has been returned according to the local time.

Advertisements