Given the name of any weekday as a string, I am trying to get its corresponding integer number using JavaScript's Date object.
Here is what I have tried:
const birthday = new Date('January 04, 2020');
const day_number = birthday.getDay();
console.log(day_number);
In the above example, I knew the date and hence, I could apply the getDay() on it to retrieve the integer value of that day. The above code logs the number "6" as the value and that is correct (the integer value of Sunday being "0", Monday being "1", and so on... till the integer value of Saturday becomes "6").
What I am trying to achieve:
I want to supply the weekday directly and get it's corresponding integer value. Example follows:
const weekday = 'Saturday';
const day_number = weekday.getDay();
console.log(day_number);
When I run the above code, I get the following error message:
weekday.getDay is not a function
What should I change in the above code so that when I supply the weekday directly using const weekday = 'Saturday';
, I get the value of console.log(day_number);
as 6
?
Please note:
- I am trying to achieve this natively using JS date object.
- I need to pass any other weekday as the string and get it's corresponding integer value.
Edit 1:
I looked through the post Day Name from Date in JS and it is NOT what I am looking for. The accepted solution in that post gives the result as "Day Name", while I am trying to output the "Integer value of the Day Name".