0

I tried to search for "Calculating the Week for a given Date" and could not find accurate solution in a easier way. Here is what I have tried:

Let's assume the date specified is 'd'

getWeekOfDay: function(d){
   var date1 = new Date(d.getFullYear(), d.getMonth(), d.getDate());
   var yearWeek;
   var firstMondayOfWeek1 = 
   this.getMondayOfWeekOneOfAGivenYear(date1.getFullYear());
   var weekNumber = Math.ceil((((date1 - firstMondayOfWeek1) / 86400000) + 1) / 7);
   yearWeek = date1.getFullYear() + "." + weekNumber;

   if(weekNumber <= 0 ){    // Jan 01 2012;
      //date falls in last week of previous year
      firstMondayOfWeek1 = this.getMondayOfWeekOneOfAGivenYear(date1.getFullYear() - 1);
      weekNumber = Math.ceil((((date1 - firstMondayOfWeek1) / 86400000) + 1) / 7);
      yearWeek = (date1.getFullYear() - 1) + "." + weekNumber;
   }

   if(weekNumber === 53 ){  // Dec 29 2014; Dec 28 2020
      var Dec31 = new Date(date1.getFullYear(), 11, 31);
      if(Dec31.getDay() < 4){
      yearWeek = (date1.getFullYear() + 1) + "." + 1;
   }
 }
 return yearWeek;
},

getMondayOfWeekOneOfAGivenYear: function(year){
    //4th Jan always falls in Week1 of that year
    var fouthJan = new Date(year, 0, 4);//
    var day = fouthJan.getDay();
    if (fouthJan.getDay() === 0) {  //Sunday
       day = 7;
    }
    var firstMondayofW1 = new Date(fouthJan);
    firstMondayofW1.setDate(firstMondayofW1.getDate() + (1 - day) * 1);
    return firstMondayofW1; 
},
Arvind
  • 1
  • 3
  • 1
    You are doing it in way too complicated way, let momentjs handle it for you https://stackoverflow.com/questions/25953551/moment-js-get-the-week-number-based-on-a-specific-day-also-past-years – Umair Abid May 11 '18 at 08:54
  • 2
    Just a heads up: week numbering is locale-dependent. In some countries, the first week of the year starts on the first Monday of the year; in others, the first week of the year is whatever week contains January 1st. If there's any chance for this to be an issue, it's best to let a library like moment.js handle it, like @UmairAbid suggested. – Máté Safranka May 11 '18 at 09:04

0 Answers0