1

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:

  1. I am trying to achieve this natively using JS date object.
  2. 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".

Devner
  • 6,825
  • 11
  • 63
  • 104
  • 1
    Does this answer your question? [Day Name from Date in JS](https://stackoverflow.com/questions/24998624/day-name-from-date-in-js) – Mureinik Jan 04 '20 at 21:14
  • Don't think it's possible to do this through JS `Date` objects. After all a `Date` represents a particular point in time, and you're trying to extract some metadata about repeating occurrences. Just make an array with all the week days and look up the numbers from there - it's not like weekdays are going to change or anything. – VLAZ Jan 04 '20 at 21:18
  • `Object.defineProperty(String.prototype, "getDay", { value: function(){ return { Sunday: 0, Monday: 1, /*...*/ Saturday: 6 }[this]; } });`, note that this sounds like bad design. – ASDFGerte Jan 04 '20 at 21:19
  • @Mureinik he wants to do the reverse of that answer. ASDFGerte is right for both implementation and concerns. – Eldar Jan 04 '20 at 21:21
  • @Mureinik That does NOT give me the integer value of the weekday! – Devner Jan 04 '20 at 21:33
  • @VLAZ Yes, that's what I thought of as an alternative, but wanted to achieve this result using pure native JS code. – Devner Jan 04 '20 at 21:34
  • @ASDFGerte I am not sure how I can use this. – Devner Jan 04 '20 at 21:35
  • `["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]` is pure native JavaScript – VLAZ Jan 04 '20 at 21:36
  • All you need to do is execute that line before your snippet, and it works. Note again, although this makes your snippet work, i am still doubting the design of that snippet (this doesn't sound like a task, for which one would extend the prototype). However, that's not my concern. You ask "how to make X work", i give "how to make X Work". – ASDFGerte Jan 04 '20 at 21:38
  • @VLAZ Agreed, that it is pure JS solution, while I was trying to get a pure JS + JS Date Object solution. Hope that makes sense. – Devner Jan 04 '20 at 21:44
  • Yeah just use an array key : value Saturday : 6 – Stefan Avramovic Jan 04 '20 at 22:07
  • Day names are proper nouns and language specific - so if this is running in a browser, the browser may have no idea what "Saturday" means. – symcbean Jan 05 '20 at 00:42

2 Answers2

1

One way is to use a function for it.

Here's an example that calculates the weekday number for both types.

function getWeekdayNumber (str) {
    let date = new Date(str);
    if (date.toString() === 'Invalid Date')
     return str.includes('Monday') ? 1
          : str.includes('Tuesday') ? 2
          : str.includes('Wednesday') ? 3
          : str.includes('Thursday') ? 4
          : str.includes('Friday') ? 5
          : str.includes('Saturday') ? 6
          : str.includes('Sunday') ? 0
          : undefined;

    return date.getDay();
}

let weekday = 'Saturday'; 
console.log(weekday + ' --> ' + getWeekdayNumber(weekday));

let birthday = 'January 04, 2020'; 
console.log(birthday + ' --> ' + getWeekdayNumber(birthday));
LukStorms
  • 28,916
  • 5
  • 31
  • 45
  • By far, your solution is the most complete solution that considers both the Weekday and Date and gives the Integer value that I was looking for. Purely AWESOME!!! Thanks a ton!!! – Devner Jan 05 '20 at 08:49
0

The following is based on extension of built–in objects, which is unadvisable.

To do this with the built–in Date object, you can extend it with a getDaynumber method like:

Date.getDaynumber = function(s) {
  let weekdays = ['sunday','monday','tuesday','wednesday',
                  'thursday','friday','saturday',
                  'sun','mon','tue','wed','thu','fri','sat',
                  'su','mo','tu','we','th','fr','sa'];
  let num = weekdays.indexOf(s.toLowerCase());
  return num == -1? void 0 : num % 7;
};

['Saturday','Th','Fri','foo'].forEach(s => console.log(s + ': ' + Date.getDaynumber(s)));

You can also extend the built–in String.prototype, again not recommended but here's how to do it:

String.prototype.getWeekday = function() {
  let weekdays = ['sunday','monday','tuesday','wednesday',
                  'thursday','friday','saturday',
                  'sun','mon','tue','wed','thu','fri','sat',
                  'su','mo','tu','we','th','fr','sa'];
 let num = weekdays.indexOf(this.valueOf().toLowerCase());
 return num == -1? void 0 : num % 7;
};

['Saturday','Th','Fri','foo'].forEach(s => console.log(s + ': ' + s.getWeekday()));

The method can be optimised, but it shows the basic principle.

RobG
  • 142,382
  • 31
  • 172
  • 209