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:
Returns:
- An integer representing the hour of the day (from 0 to 23).
Example 1: Getting UTC Hour for a Specific Date
Output:
Explanation:
- The
Date
object represents October 22, 2024, at 15:30:00 UTC. ThegetUTCHours()
method returns15
, which corresponds to 3 PM in UTC.
Example 2: Getting UTC Hour for a Local Time
Output:
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()
returns9
.
Example 3: Getting UTC Hour for a Date Near Midnight
Output:
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()
returns2
.
Example 4: Getting UTC Hour for a Date Object Created with UTC
Output:
Explanation:
- The
Date.UTC()
method creates a date object for October 22, 2024, at 15:30:00 in UTC. ThegetUTCHours()
method will return15
, confirming that the hour is indeed 3 PM in UTC.
Summary:
date.getUTCHours()
returns the hour of aDate
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.