3

I get date from API like that 6-21-2021 and how can I grab day from this? I have created array of week days

let days: string[] = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
];

and is there any solution to get day?

callmenikk
  • 1,358
  • 2
  • 9
  • 24
  • 1
    Use date fns they have some helper functions. https://date-fns.org/v2.22.1/docs/getDate – Rajendran Nadar Jun 20 '21 at 20:09
  • The way you **should** do this is to parse the string, avoiding the built–in parser and use built–in functions like [*Intl.DateTimeFormat#format*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) or [*Date#toLocaleString*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) with appropriate options, e.g. `let [m,d,y] = '6-21-2021'.split(/\D/); new Date(y,m-1,d).toLocaleString('default',{weekday:'long'})`. – RobG Jun 21 '21 at 00:26

2 Answers2

0

You can use Date#getDay:

const days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];

const parseDate = str => {
  const parts = str.split('-');
  return new Date(parts[2], parts[0]-1, parts[1]);
}

const date = parseDate("6-21-2021");
const day = days[date.getDay()];

console.log(day);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • 2
    Parsing of unsupported formats with the built–in parser is implementation dependent and strongly discouraged. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) The above returns *undefined* in Safari. – RobG Jun 20 '21 at 23:44
  • I had that issue, that was lots of struggling but at least done, first of all i split my date and created new array and with indexes i replaced their places in new one and changed commas to `-` this – callmenikk Jun 21 '21 at 00:46
0

Also, you can use localized week day name:

const date = new Date('6-21-2001')
const dayName = date.toLocaleString(window.navigator.language, { weekday: 'long' })
console.log({ dayName })
Sergio Belevskij
  • 2,478
  • 25
  • 24
  • I get `{"dayName": "Invalid Date"}`, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Jun 20 '21 at 23:46