获取每个月有几周,开始到结束的时间

const getYMWeek = (year, month) => {
    let list = [];
    let d1;
    let weekCount;
    let d = new Date();
    // what day is first day
    d.setFullYear(year, month-1, 1); //  设置时间为2018-01-01
    let w1 = d.getDay(); //  这天是周几
    if (w1 === 0) w1 = 7; // 1,2,3,4,5,6,7
    // total day of month
    d.setFullYear(year, month, 0); //  设置时间是2018-02-31
    let dd = d.getDate(); // 每个月的总天数
    // console.log(dd);
    // first Monday
    if (w1 !== 1) {
        d1 = (7-w1)+2;
    } else {
        d1 = 1;
    }
    weekCount = Math.ceil(((dd-d1)+1)/7); // 这个月有多少周
    for (let i = 0; i < weekCount; i+=1 ) {
        let monday = d1+(i*7); // 每周周一
        let sunday = monday + 6; // 每周周日
        let from = month+"月"+ monday +"日";
        let to;
        if (sunday <= dd) {
            to = month+"月"+ sunday +"日";
        } else {
            d.setFullYear(year, month-1, sunday);
            to = (d.getMonth()+1)+"月"+d.getDate()+"日";
        }
        let json = {
           'year':year,
           'month':month,
           'week':i+1,
           'weekTime':from + "-" + to
        };
        list.push(json);
    }
    return list;
};

入参是年,月。也就是获取某年某月的week

返回值是json ,值有year,month,week,weekTime。

也就是获取某年某月有几周,每周开始和结束的时间

你可能感兴趣的:(web前端,JavaScript)