JavaScript date.getUTCMonth() method
The date.getUTCMonth()
method in JavaScript returns the month (from 0 to 11) of a specified Date
object according to Universal Coordinated Time (UTC). This method is useful for obtaining the month of a date without considering local time zone differences.
Syntax:
Returns:
- An integer representing the month of the year (from 0 for January to 11 for December).
Example 1: Getting UTC Month for a Specific Date
Output:
Explanation:
- The
Date
object represents October 22, 2024, at 15:30:00 UTC. ThegetUTCMonth()
method returns9
because months are zero-indexed (0 for January, 1 for February, ..., 9 for October).
Example 2: Getting UTC Month for a Local Time
Output:
Explanation:
- If the local time is November 1, 2024, at 12:00 PM, it will convert to UTC based on your local timezone. If your local timezone is UTC-3, the time would be 3:00 PM UTC on November 1. The
getUTCMonth()
method returns10
, indicating November.
Example 3: Getting UTC Month for a Date Near Midnight
Output:
Explanation:
- If your local timezone is UTC-3, then the local time of 23:59:59 on October 31 will convert to 02:59:59 UTC on November 1. Thus,
getUTCMonth()
returns10
, representing November.
Example 4: Getting UTC Month 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. ThegetUTCMonth()
method returns9
, confirming the correct month (October).
Summary:
date.getUTCMonth()
returns the month of aDate
object in UTC, ranging from 0 (January) to 11 (December).- This method is helpful for working with months in a consistent manner, independent of local timezone adjustments.