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:

date.getHours();

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

const date = new Date('2024-10-22T15:30:00'); // October 22, 2024, 15:30 (3:30 PM) const hours = date.getHours(); console.log(hours);

Output:

15

Explanation:

  • The time in the Date object is 15:30 (3:30 PM). The getHours() method returns 15, representing 3 PM in a 24-hour format.

Example 2: Getting the Current Hour

const now = new Date(); // Current date and time const currentHour = now.getHours(); console.log(currentHour);

Output:

(Depends on the current hour)

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 be 20.

Example 3: Midnight Example

const date = new Date('2024-10-22T00:00:00'); // Midnight on October 22, 2024 const hours = date.getHours(); console.log(hours);

Output:

0

Explanation:

  • The time is set to midnight (00:00), so getHours() returns 0, representing midnight.

Summary:

  • date.getHours() returns the hour of the day from a Date 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.