JavaScript date.getHours() method
The date.getHours()
method in JavaScript returns the hour (from 0 to 23) for a specific Date
object, according to local time.
Syntax:
Returns:
- A number between 0 and 23 that represents the hour for the specified date.
Example 1: Getting the Hour for a Specific Date and Time
Output:
Explanation:
- The time in the
Date
object is 15:30 (3:30 PM). ThegetHours()
method returns15
, representing 3 PM in a 24-hour format.
Example 2: Getting the Current Hour
Output:
Explanation:
- This retrieves the current hour of the day in the user's local time. For example, if it's 11:00 AM, the output will be
11
; if it's 8:00 PM, the output will be20
.
Example 3: Midnight Example
Output:
Explanation:
- The time is set to midnight (00:00), so
getHours()
returns0
, representing midnight.
Summary:
date.getHours()
returns the hour of the day from aDate
object, ranging from 0 (midnight) to 23 (11 PM).- It is useful for extracting the hour component of a date and time in a 24-hour format.