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:
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
Output:
Explanation:
- The
Date
object represents October 22, 2024, which is a Tuesday. ThegetUTCDay()
method returns2
, indicating that the day is Tuesday (0 = Sunday, 1 = Monday, 2 = Tuesday).
Example 2: Getting UTC Day for a Local Time
Output:
Explanation:
- Even if the date is created in local time,
getUTCDay()
returns2
for October 22, 2024, since it corresponds to the same day in UTC.
Example 3: Getting UTC Day for a Date Near Midnight
Output:
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()
returns3
, indicating that it is Wednesday in UTC.
Example 4: Getting UTC Day for a Date Object Created with UTC
Output:
Explanation:
- The
Date.UTC()
method creates a date object for October 22, 2024, in UTC. ThegetUTCDay()
method will return2
, confirming that this date is indeed a Tuesday in UTC.
Summary:
date.getUTCDay()
returns the day of the week for aDate
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.