Categories
JavaScript Answers

How to get the day of the week from the day number in JavaScript?

Spread the love

To get the day of the week from the day number in JavaScript, we use the date getDay method.

For instance, we write

const dayOfTheWeek = (day, month, year) => {
  const weekday = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  return weekday[new Date(`${month}/${day}/${year}`).getDay()];
};

console.log(dayOfTheWeek(3, 11, 2022));

to define the dayOfTheWeek function.

In it, we put the month, day and year into a string to create a Date object from it.

Then we call getDay to get the day of the week with 0 being Sunday, 1 being Monday, etc.

We use that returned number as the index of weekday to get the day of the week.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *