Categories
JavaScript Answers

How to Get the Day of the Week and the Month of the Year with JavaScript?

Spread the love

To get the day of the week, we can use the getDay method with an array of day strings to get the day of the week.

For instance, we can write:

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

const dt = new Date(2021, 1, 1)
const day = days[dt.getDay()];
console.log(day)

We have the days array with day names in it.

Then create the dt date object with the Date constructor.

Next, we call getDay on dt to get the day index starting with 0 for Sunday to 6 for Saturday.

And we pass that into days to get the day name of the date.

Therefore day is 'Monday' .

Get the Month of the Year

To get the day of the week, we can use the getMonth method with an array of day strings to get the month of the year.

For instance, we can write:

const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const dt = new Date(2021, 1, 1)
const month = months[dt.getMonth()];
console.log(month)

We have the months array with the month names.

We have the days array with day names in it.

Then create the dt date object with the Date constructor.

Next, we call getMonth on dt to get the month index starting with 0 for January to 11 for December.

And we pass that into months to get the day name of the date.

Therefore month is 'February' .

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 *