José Cabrera
José Cabrera

Reputation: 33

Javascript Date getDay() format issue

I'm having a issue is JS trying to get the day of the week of a specific date:

const searchDate = "2021-02-04";
const serchDateDayOfWeek = new Date( searchDate ).getDay();
console.log( serchDateDayOfWeek ) // => 3

I assumed that the result would be 4 (Thursday) but it is 3 (Wednesday).

What would be the correct way to get the day of week value without modifying the format of the seachDate?

Thanks in advance!

Upvotes: 1

Views: 440

Answers (2)

gricn
gricn

Reputation: 73

Update:

In MDN, Date constructors syntax includes

new Date()
new Date(value)
new Date(dateString)
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

"2021-02-04" is a dateString which is strongly discouraged by MDN( This reference is wildly distributed in Internet ^v^ )

Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.

Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

In brief, there are many international standards that create conflicts in dateString mode. Different browsers may use different standards, that is "browser differences". So that's why I run your code in mdn, the output is 4 which is different from yours.

There is another answer facing the same situation as yours, and the output is smaller than the correct result by 1 as yours.

If you Google, you will find many people are trapped. I think this answer should be filed with other answers like:

So, I strongly recommend don't use dateString to construct Date. Just use new Date(2021, 02, 04), you will get the correct answer.

Upvotes: 2

Gareth Compton
Gareth Compton

Reputation: 149

To solve for this, you need to make an array containing names of the days in order. And on the index end of the array, put new Date().getDay() inside the index of the array, and should return a result.

console.log([
     "Sunday",
     "Monday",
     "Tuesday",
     "Wendesday",
     "Thursday",
     "Friday",
     "Saturday"
][
    new Date().getDay()
])

The above will assign a named day based on the index number new Date().getDay() produces.

Upvotes: 1

Related Questions