how to get day from date format

Viewed 1109

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?

2 Answers

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);

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 })

Related