【问题标题】:JS - dates of month, by week grouping.JS - 月份日期,按周分组。
【发布时间】:2016-04-13 06:48:03
【问题描述】:

我正在尝试记录。写周数,然后是该周的天数。例如,如果您输入 2016 年 4 月作为您想要的月份,它将显示 weekNum
那么在第 1 周,第一个是星期五,第二个是星期六。然后第 2 周第 3 周是星期日,第 4 周是星期一,以此类推整个月。

//variables
var reqMon;
var todaysDate = new Date();
var currYr = todaysDate.getFullYear();
var currMon = todaysDate.getMonth();
var currDate = todaysDate.getDate();
var currDay = todaysDate.getDay();

//creates a month array.
var monthArray = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
//creates a day array.
var weekDaysArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
//creates an array for how many days in each month. 
var maxMonthlyDays = new Array("31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31");

//prompts user for numeric month.
var reqMon = parseInt(prompt("Enter desired month (Jan = 1, Dec = 12)"));

//validates users month input.
while (reqMon == "" || reqMon < 1 || reqMon > 12) { 
    reqMon = prompt("Invalid Entry. Please enter the month number again.")
}

//Step 3B. 
document.write(reqMon + "/" + currDate + "/" + currYr + "<br /><br />");

//Step 4.
document.write(monthArray[reqMon -1] + " " + currYr + "<br /><br />");

var dateComb = (reqMon + "/1/" + currYr);
var userIdate = new Date(dateComb);
var userDay = new Date(dateComb).getDay();
var userDate = new Date(dateComb).getDate();
var maxDays = maxMonthlyDays[reqMon -1];
var numberWeeks = maxMonthlyDays[reqMon - 1] / 6;

// ****************  STEP 5 **************.
//loops through weeks of month.
for (x = 1; x <= maxMonthlyDays[reqMon] / 6; x++) {
    document.write("<b>Week " + x + "<br /></b>");

    while (userDay <= 6 && userDate <= maxMonthlyDays[reqMon]) { 
        document.write(weekDaysArray[userDay] + " " + userDate + "<br />");
        userDay++;
        userDate++;
    }
}

我可以得到 weekNum 迭代并输出到屏幕,我可以得到所需月份的总天数来迭代和输出。但我似乎无法获得“仅在正确的 weekNum 下输出 1、2、3 等天。

提前致谢。

【问题讨论】:

    标签: javascript loops calendar iteration


    【解决方案1】:

    试试这个,不过我不确定你到底需要什么。

        for (x = 1; x <= numberWeeks; x++) {
            document.write("<b>Week " + x + "<br /></b>");
            while (userDay <= 6 && userDate <= maxDays) {
                document.write(weekDaysArray[userDay] + " " + userDate + "<br />");
                userDay++;
                userDate++;
            }
            userDay = 0;
        }
    

    【讨论】: