JS - 按月分组的月份日期。

时间:2016-04-13 06:48:03

标签: javascript loops calendar iteration

我试图记录。写周数,然后是那周的日子。例如,如果您输入2016年4月作为您所需的月份,它将显示weekNum
然后在第1周,1日是星期五,2日是星期六。然后第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,等等的日子。

提前谢谢。

1 个答案:

答案 0 :(得分: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;
    }