EN
JavaScript - day name for the first day of month
3
points
In this article, we would like to show you how to get the first day name of the indicated month in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const year = 2021;
const month = 7; // 0 - January, ..., 7 - August, ..., 11 - December
const date = new Date(year, month, 1);
const day = days[date.getDay()];
console.log(day); // Sunday
Where in the above code, we:
- use an array with names of the weekdays,
- create a date that represents the first day in the month - it is
Date(year, month, 1)
, - get day index in the week using
getDay()
method - it counts days from0
to6
, staring from Sunday, - get the day name from the array using the day index.
Reusable code example
// ONLINE-RUNNER:browser;
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const getFirstDayName = (year, month) => {
const date = new Date(year, month, 1); // first day of the month
return days[date.getDay()]; // getting day of the week (counted from 0 to 6 - Sunday as first)
};
// Usage example:
console.log(getFirstDayName(2021, 0)); // Friday // 0 - January
console.log(getFirstDayName(2021, 1)); // Monday // 1 - February
console.log(getFirstDayName(2021, 2)); // Monday // 2 - March
Output:
Friday
Monday
Monday