JavaScript date.getUTCDay() method


The date.getUTCDay() method in JavaScript returns the day of the week for a specified Date object according to Universal Coordinated Time (UTC). The method returns a number between 0 and 6, where 0 represents Sunday, 1 represents Monday, and so on, up to 6 which represents Saturday.

Syntax:

date.getUTCDay();

Returns:

  • An integer between 0 and 6 that represents the day of the week in UTC.

Example 1: Getting UTC Day for a Specific Date

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

Output:

2

Explanation:

  • The Date object represents October 22, 2024, which is a Tuesday. The getUTCDay() method returns 2, indicating that the day is Tuesday (0 = Sunday, 1 = Monday, 2 = Tuesday).

Example 2: Getting UTC Day for a Local Time

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

Output:

2

Explanation:

  • Even if the date is created in local time, getUTCDay() returns 2 for October 22, 2024, since it corresponds to the same day in UTC.

Example 3: Getting UTC Day for a Date Near Midnight

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

Output:

3

Explanation:

  • If your local timezone is UTC-3, the UTC equivalent of October 22, 2024, at 23:59:59 local time would be October 23, 2024, at 02:59:59 UTC. Thus, getUTCDay() returns 3, indicating that it is Wednesday in UTC.

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

const utcDate = new Date(Date.UTC(2024, 9, 22)); // October is month 9 (0-indexed) const utcDayCreated = utcDate.getUTCDay(); console.log(utcDayCreated);

Output:

2

Explanation:

  • The Date.UTC() method creates a date object for October 22, 2024, in UTC. The getUTCDay() method will return 2, confirming that this date is indeed a Tuesday in UTC.

Summary:

  • date.getUTCDay() returns the day of the week for a Date object in UTC, ranging from 0 (Sunday) to 6 (Saturday).
  • This method is helpful for applications that need to consider the day of the week in a time zone-independent manner.