Languages
[Edit]
EN

JavaScript - day name for the first day of month

3 points
Created by:
Remy-Lebe
802

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:

  1. use an array with names of the weekdays,
  2. create a date that represents the first day in the month - it is Date(year, month, 1),
  3. get day index in the week using getDay() method - it counts days from 0 to 6, staring from Sunday,
  4. 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

    See also

    1. JavaScript - English day names

    References

    1. Date() constructor syntax - JavaScript
    Donate to Dirask
    Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
    Join to our subscribers to be up to date with content, news and offers.

    Cross technology - day name for the first day of month

    Native Advertising
    🚀
    Get your tech brand or product in front of software developers.
    For more information Contact us
    Dirask - we help you to
    solve coding problems.
    Ask question.

    ❤️💻 🙂

    Join