Categories
JavaScript Answers

How to determine the day of the week with JavaScript?

Spread the love

Sometimes, we want to determine the day of the week with JavaScript.

In this article, we’ll look at how to determine the day of the week with JavaScript.

How to determine the day of the week with JavaScript?

To determine the day of the week with JavaScript, we can call the JavaScript date’s getDay method.

We can also use toLocaleString to return date as a human readable string.

For instance, we write:

const d = new Date(2022, 1, 1).getDay();
console.log(d)

We call getDay on the Date instance to return the day of the week as a number.

It ranges from 0 to 6, where 0 is Sunday and 6 is Saturday.

Therefore, since Feb 1, 2022 is a Tuesday, we get 2 for the value of d.

To use toLocateString we write:

const d = new Date(2022, 1, 1).toLocaleDateString('en', {
  weekday: 'long'
})
console.log(d)

We call toLocaleString with the locale and object with the weekday property to return the day of the week.

Therefore, we get 'Tuesday' as the value of d.

Conclusion

To determine the day of the week with JavaScript, we can call the JavaScript date’s getDay method.

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 *