1

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.

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks!! it really was problem with the time of the date!
@Alon glad to help! :) Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.