Reputation:
I create function that loop on dates and enter then to array according to the week and the day in the week.
This is the code of the loop and the functions.
var weeks = [];
//get the week number of the date;
var getWeek = function(date) {
var onejan = new Date(date.getFullYear(), 0, 1);
return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};
var curr = new Date();
//get the first day of the week
var startDay = new Date(curr.setDate(curr.getDate() - curr.getDay()));
//endDay="2015/9/30"
var endDay = new Date(2015, 8, 30);
while (startDay < endDay) {
if (weeks[getWeek(startDay)] == undefined) {
weeks[getWeek(startDay)] = [];
}
weeks[getWeek(startDay)][startDay.getDay()] = startDay.toString();
var newDate = startDay.setDate(startDay.getDate() + 1);
startDay = new Date(newDate);
}
console.log(weeks);
The code runs and I dont know why it "confuse" with some dates but like the today 2015.9.19 it put it on month 39 but when I run the getWeek on this date it says 38.
var getWeek = function(date) {
var onejan = new Date(date.getFullYear(), 0, 1);
return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};
alert(getWeek(new Date("2015/9/19")));
so I dont understand what is wrong in the loop.
Upvotes: 1
Views: 236
Reputation: 8715
There is nothing wrong with the loop - the problem is with how you initialize you start date. Hours, minutes and seconds in particular.
Compare these:
getWeek(new Date()); // 39
getWeek(new Date(2015, 8, 19)); // 38
getWeek(new Date(2015, 8, 19, 1)); // 39
I guess that error accumulates, when you do Math.ceil()
- you might want a deeper debugging for that.
Anyway, here's how your code may look like:
var weeks = [];
//get the week number of the date;
var getWeek = function(date) {
var onejan = new Date(date.getFullYear(), 0, 1);
return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};
var curr = new Date();
// -----------------
// Subtract the date, because there is a chance we will get a prev month.
curr.setDate(curr.getDate() - curr.getDay());
// Initialize with diff constructor, so m:h:s will be 0.
var startDay = new Date(curr.getFullYear(), curr.getMonth(), curr.getDate());
// -----------------
//endDay="2015/9/30"
var endDay = new Date(2015, 8, 30);
while (startDay < endDay) {
if (weeks[getWeek(startDay)] == undefined) {
weeks[getWeek(startDay)] = [];
}
weeks[getWeek(startDay)][startDay.getDay()] = startDay.toString();
var newDate = startDay.setDate(startDay.getDate() + 1);
startDay = new Date(newDate);
}
console.log(weeks);
Upvotes: 1