How do I get all days of the week in a month?

  • 0
    Using momentjs you can do this:
    [...Array(moment().daysInMonth()).keys()].map((_, i) => i + 1)

    But I need something like this:
    [{
        week: "Th",
        label: "1"   
    },
    {
        week: "F",
        label: "2"   
    },
        .....
    ]
    JavaScript Piper Kent, Nov 22, 2020

  • 1 Answers
  • 0
    const formatter = new Intl.DateTimeFormat('en-US', {
    weekday: 'short'
    });

    const getMonthDays = (year, month) => {
    const date = new Date(year, month + 1, 0);
    const count = date.getDate();
    const days = [];

    for (let day = 1; day <= count; day++) {
    date.setDate(day);

    days.push({
    week: formatter.format(date),
    label: date.getDate()
    });
    }

    return days;
    };

    getMonthDays(2020, 8); // Вернет дни сентября 2020 года
    /**
    [
    { week: 'Tue', label: 1 },
    { week: 'Wed', label: 2 },
    { week: 'Thu', label: 3 },
    { week: 'Fri', label: 4 },
    { week: 'Sat', label: 5 },
    { week: 'Sun', label: 6 },
    { week: 'Mon', label: 7 },
    { week: 'Tue', label: 8 },
    { week: 'Wed', label: 9 },
    { week: 'Thu', label: 10 },
    { week: 'Fri', label: 11 },
    { week: 'Sat', label: 12 },
    { week: 'Sun', label: 13 },
    { week: 'Mon', label: 14 },
    { week: 'Tue', label: 15 },
    { week: 'Wed', label: 16 },
    { week: 'Thu', label: 17 },
    { week: 'Fri', label: 18 },
    { week: 'Sat', label: 19 },
    { week: 'Sun', label: 20 },
    { week: 'Mon', label: 21 },
    { week: 'Tue', label: 22 },
    { week: 'Wed', label: 23 },
    { week: 'Thu', label: 24 },
    { week: 'Fri', label: 25 },
    { week: 'Sat', label: 26 },
    { week: 'Sun', label: 27 },
    { week: 'Mon', label: 28 },
    { week: 'Tue', label: 29 },
    { week: 'Wed', label: 30 }
    ]
    */
    Levi Holt

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!