The getUTCDay()
method in JavaScript is a part of the Date
object and is used to get the day of the week (0-6) for a given date object, in the UTC time zone. This can be useful for getting the day of the week in a specific time zone, or for working with dates in a consistent time zone.
Here’s an example of how to use getUTCDay()
to get the current day of the week in UTC time:
let date = new Date();
let day = date.getUTCDay();
console.log(day); // Outputs the current day of the week in UTC time (0-6)
You can also pass a date object as an argument to getUTCDay()
to get the day of the week for a specific date in UTC time:
let date = new Date(2022, 0, 1, 11, 30, 0); // January 1, 2022 at 11:30:00 (local time)
let day = date.getUTCDay();
console.log(day); // Outputs 6
Note that the getUTCDay()
method returns the day of the week as a number, with 0 representing Sunday, 1 representing Monday, and so on. If you want to get the day of the week as a name, you can use an array of day names and access the appropriate element based on the day number returned by getUTCDay()
.
Here’s an example of how to get the day of the week name for a specific date in UTC time:
let date = new Date(2022, 0, 1, 11, 30, 0); // January 1, 2022 at 11:30:00 (local time)
let dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let day = date.getUTCDay();
console.log(dayNames[day]); // Outputs "Saturday"
In addition to getting the day of the week, you can also use the setUTCDay()
method to set the day of the week for a date object in UTC time. However, this method is not widely supported and may not work in all browsers.
Leave a Reply