JavaScript date.getUTCHours() method


The date.getUTCHours() method in JavaScript returns the hour (from 0 to 23) of a specified Date object according to Universal Coordinated Time (UTC). This method is particularly useful for obtaining the hour of a date without considering local time zone differences.

Syntax:

date.getUTCHours();

Returns:

  • An integer representing the hour of the day (from 0 to 23).

Example 1: Getting UTC Hour for a Specific Date

const date = new Date('2024-10-22T15:30:00Z'); // October 22, 2024, at 15:30:00 UTC const utcHour = date.getUTCHours(); console.log(utcHour);

Output:

15

Explanation:

  • The Date object represents October 22, 2024, at 15:30:00 UTC. The getUTCHours() method returns 15, which corresponds to 3 PM in UTC.

Example 2: Getting UTC Hour for a Local Time

const localDate = new Date('2024-10-22T12:00:00'); // October 22, 2024, at 12:00 PM local time const utcHourFromLocal = localDate.getUTCHours(); console.log(utcHourFromLocal);

Output:

9

Explanation:

  • If the local time zone is UTC-3 (for example, Brazil), the local time of 12:00 PM will convert to 9:00 AM UTC. Therefore, getUTCHours() returns 9.

Example 3: Getting UTC Hour for a Date Near Midnight

const nearMidnightLocal = new Date('2024-10-22T23:59:59'); // October 22, 2024, at 23:59:59 local time const utcHourNearMidnight = nearMidnightLocal.getUTCHours(); console.log(utcHourNearMidnight);

Output:

2

Explanation:

  • If your local timezone is UTC-3, then the local time of 23:59:59 on October 22 will be 02:59:59 UTC on October 23. Thus, getUTCHours() returns 2.

Example 4: Getting UTC Hour for a Date Object Created with UTC

const utcDate = new Date(Date.UTC(2024, 9, 22, 15, 30, 0)); // October 22, 2024, at 15:30:00 UTC const utcHourCreated = utcDate.getUTCHours(); console.log(utcHourCreated);

Output:

15

Explanation:

  • The Date.UTC() method creates a date object for October 22, 2024, at 15:30:00 in UTC. The getUTCHours() method will return 15, confirming that the hour is indeed 3 PM in UTC.

Summary:

  • date.getUTCHours() returns the hour of a Date object in UTC, ranging from 0 to 23.
  • This method is helpful for applications that need to work with UTC time consistently, independent of local timezone adjustments.