JavaScript Date getHours()
Syntax & Examples
Date.getHours() method
The getHours() method of the Date object in JavaScript returns the hour (0 – 23) in the specified date according to local time.
Syntax of Date.getHours()
The syntax of Date.getHours() method is:
getHours()This getHours() method of Date returns the hour (0 – 23) in the specified date according to local time.
Return Type
Date.getHours() returns value of type Number.
✐ Examples
1 Using getHours() to get the hour of a specific date
In JavaScript, we can use the getHours() method to get the hour from a Date object.
For example,
- We create a new Date object
daterepresenting January 15, 2021, at 15:30:00. - We use the
getHours()method to get the hour fromdate. - The hour is stored in the variable
hour. - We log
hourto the console usingconsole.log()method.
JavaScript Program
const date = new Date('2021-01-15T15:30:00');
const hour = date.getHours();
console.log(hour);Output
15
2 Using getHours() with the current date
In JavaScript, we can use the getHours() method to get the current hour from the current date.
For example,
- We create a new Date object
todayrepresenting the current date and time. - We use the
getHours()method to get the current hour fromtoday. - The current hour is stored in the variable
currentHour. - We log
currentHourto the console usingconsole.log()method.
JavaScript Program
const today = new Date();
const currentHour = today.getHours();
console.log(currentHour);Output
13
3 Using getHours() with a specific date in the past
In JavaScript, we can use the getHours() method to get the hour from a specific date in the past.
For example,
- We create a new Date object
pastDaterepresenting July 4, 1776, at 12:00:00. - We use the
getHours()method to get the hour frompastDate. - The hour is stored in the variable
pastHour. - We log
pastHourto the console usingconsole.log()method.
JavaScript Program
const pastDate = new Date('1776-07-04T12:00:00');
const pastHour = pastDate.getHours();
console.log(pastHour);Output
12
Summary
In this JavaScript tutorial, we learned about getHours() method of Date: the syntax and few working examples with output and detailed explanation for each example.