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:

date.getUTCMonth();

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

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

Output:

9

Explanation:

  • The Date object represents October 22, 2024, at 15:30:00 UTC. The getUTCMonth() method returns 9 because months are zero-indexed (0 for January, 1 for February, ..., 9 for October).

Example 2: Getting UTC Month for a Local Time

const localDate = new Date('2024-11-01T12:00:00'); // November 1, 2024, at 12:00 PM local time const utcMonthFromLocal = localDate.getUTCMonth(); console.log(utcMonthFromLocal);

Output:

10

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 returns 10, indicating November.

Example 3: Getting UTC Month for a Date Near Midnight

const nearMidnightLocal = new Date('2024-10-31T23:59:59'); // October 31, 2024, at 11:59:59 PM local time const utcMonthNearMidnight = nearMidnightLocal.getUTCMonth(); console.log(utcMonthNearMidnight);

Output:

10

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() returns 10, representing November.

Example 4: Getting UTC Month 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 utcMonthCreated = utcDate.getUTCMonth(); console.log(utcMonthCreated);

Output:

9

Explanation:

  • The Date.UTC() method creates a date object for October 22, 2024, at 15:30:00 in UTC. The getUTCMonth() method returns 9, confirming the correct month (October).

Summary:

  • date.getUTCMonth() returns the month of a Date 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.