0

I want a javascript function that will give the current weeknumber, then, when it has the weeknumber, get all the weeknumbers from current weeknumber - X and the same with the future, but: The currentweek has to be in the center! Examples:

Currentweek: 39, X: 3 the method should return: [38,39, 40]

Currentweek: 20 X: 4 the method should return: [18,19,20,21]

This seems really simple but: keep in mind that leap years can occur, also some years have 53 weeks

also, x can range from 3 to 30

Because this concept is a little hard to explain i have made a simplistic image:

Purpose: This will be used in a calendar sort of app, in which you scroll through weeks.

My attempts so far:

Get current week number (has worked so far, but i don't know if it'll work in 2015)

Date.prototype.getWeek = function() {
  var onejan = new Date(this.getFullYear(), 0, 1);
  var weekNumber = Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
  return weekNumber; }

Determine place in array for the current weeknumber:

myActiveSlide = Math.floor(X/2);

If even, this will round upwards, so for example, X = 4, it will return 3 as the center,

If uneven, this will give the exact center, for example: X = 3 it will return 2 as the center

That's as far as I've got, can't figure out the leap-year problems

David Thomas
  • 249,100
  • 51
  • 377
  • 410
ErikBrandsma
  • 1,661
  • 2
  • 20
  • 46

1 Answers1

0

I strongly recommend using a javascript library, such as moment.js. Here is an example of the solution among many.

  var weeks = function(currentWeek,numberOfWeeks) {
    var m = Math.floor(numberOfWeeks/2);
    var r = [];
    for (i=0;i < numberOfWeeks; i+=1) {
      var d = -1*m + i;
      r.push(moment(currentWeek).add(moment.duration(d,'week')).isoWeek())
    }
    return r;
  }


  console.log('2014-W39 3 weeks span');
  console.log(weeks('2014-W39',3));
  console.log('2014-W39 4 weeks span');
  console.log(weeks('2014-W39',4));
  console.log('2000-W52 leap year ');
  console.log(weeks('2000-W52',4));
  console.log('2004-W52 53 weeks ');
  console.log(weeks('2004-W52',5));

You can se that in action here

  • 1
    By the way, weeknumbers 1 - 9 didn't work because they had invalid format. I solved it by adding an if statement saying, if(weekNumber < 10) { weeknumber = "0" + weekNumber } – ErikBrandsma Sep 25 '14 at 07:51