I'm working on a website for a conference and some users complain that the day of the week in the dates displayed in the schedule is wrong: instead of e.g. "August 3rd (Saturday)" they see "August 3rd (Friday)". August 3rd is a Saturday, so I have no idea how this is possible, it can't be a matter of time zones because the day of the month is still correct.
Here is my function to get the name of the day of a date (the function receives the dates in the YYYY-mm-dd
format):
const dayOfWeek = (date) => {
const dateObj = new Date(date);
const day = dateObj.getDay();
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return days[day];
};
(I translated the names of the days in English for your convenience but it's in another language in my code.)
I can't see what's wrong with my code, the only explanation I can find is that getDay()
gives different results for different users but I have no idea how this is possible. I can't reproduce the issue, it works correctly for me and other (most?) users, but several users complained about this issue.
Maybe it's a locale issue and for some users the week starts on Monday? But getDay()
should always give 0
for Sunday regardless of the locale and the week starts on Monday in my locale too, so I have no idea.
All I could find googling about getDay()
giving wrong results was people wanting to use getDate()
instead but this is a different issue.
Thanks for your help!
console.log(new Date('2024-08-03').toString())
prints"Sat Aug 03 2024 02:00:00 GMT+0200 (Central European Summer Time)"
when the user uses a central European locale and"Fri Aug 02 2024 20:00:00 GMT-0400 (Eastern Daylight Time)"
when the user uses an eastern locale. As you can see, both users get different weekdays. They also get different days with.getDay()
, 5 resp. 6. I guess, you use two different function for your date string. For the date part you use UTC time and for the weekday you use local time.new Date()
would simply give you the same date regardless of the local timezone, and I used a different function to get "August 3rd" from the date string.getUTCDay()
workds, thank you to both of you.