我正在尝试使用Angular为我的应用构建日历模式。我有这样的模型
我建立年月没有问题,但不确定如何设置其他一天的周。例如,10月的第一周在第一周有28,29,30。
//code to build day
var month = 9; // hardcoded for demo.
var monthA = [];
for (var m = 0; m <= 3; m ++) {
var weeks = [];
totalDay = new Date(year, month + m + 1, 0).getDate()
//build days
for (var i = 0; i <= totalDay; i++) {
//setting up weeks
if (i % 7 == 0) {
weeks.push([]);
}
weeks[weeks.length-1].push(i);
}
var monthObj = {
month : (month + m),
weeks:weeks
}
monthA.push(monthObj);
}
以上代码将生成
monthA:
[
{
month: '10',
weeks: [
[1,2,3,4,5,6,7],
[8,9,10,11,12,13,14],
[15,16,17,18,19,20,21],
[21,22,23,24,25,26,27],
[28,29,30,31]
]
},
{
month: 'Nov',
weeks: [1,2,3,4,5,6,7] ...
}...
]
}
我希望得到
month:
[
{
month: '10',
weeks: [
[28, 29, 30, 1,2,3,4], //I haven o problem building the week from 1 to 4
[5,6,7,8,9,10,11],
[12,13,14,15,16,17,18],
[19,20,21,22,23,24,25],
[26,27,28,29,30,31,1]
]
},
{
month: '11',
weeks: [26,27,28,29,30,31,1] ...
}
]
非常感谢你的帮助!
答案 0 :(得分:1)
我刚刚制作的这个功能可以做你想做的事:
function getWeeksinMonth(year, month){ //month 1-12 based
var weeks = [];
lastDayinMonth = new Date(year, month, 0) // get last day in month
firstDayinMonth = new Date(year, month-1, 1) //get first day in month
start = new Date(firstDayinMonth.getTime()); //copy firstDay
start.setDate(start.getDate() - start.getDay() ); // set date to previous sunday
end=new Date(lastDayinMonth.getTime()); //copy lastDay
end.setDate(end.getDate() - end.getDay() ); // set date to previous sunday
if(end < lastDayinMonth){ // if previous sunday was not the lastDay itself, we want to add another week
end.setDate(end.getDate() + 7);
}
var counter=0;
var week=[]
for(;start<=end;start.setDate(start.getDate()+1)){ // traverse days
if(counter % 7==0 && counter != 0){ // every 7 days add a week
var copy=week.slice(0);
weeks.push(copy)
week=[];
}
week.push(start.getDate())
counter++
}
return weeks;
}
var weeks = getWeeksinMonth(2014,10);
for(var i=0;i<weeks.length;i++){
document.body.innerHTML+=weeks[i].toString() + '<br/>';
}
&#13;