JavaScript .getHours()

EugeneGoh_'s avatar
Published Jun 22, 2021Updated May 24, 2023
Contribute to Docs

The .getHours() method returns the hours of a date according to the local time.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

Syntax

myDate.getHours();

The return value of .getHours() is an integer number between 0 and 23, meaning the hour according to the local time.

Example

To determine if it is 10 in the morning or not:

const today = new Date('June 25, 2021 13:41:30');
if (today.getHours() === 10) {
console.log('It is 10 in the morning now.');
} else {
console.log('It is not 10 in the morning now.');
}
// Output: It is not 10 in the morning now.

Codebyte Example

The example below is runnable, and first, it defines currentTime with today’s date and time, then the result of the .getHours()method is saved in currentHour. Lastly, a console.log call prints the value to the screen:

Code
Output

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours