2

this is th javscript code i have used to get calculate the week no. from the given date....but the output i am getting is incorrect

   var dayNr   = (this.getDay() + 6) % 7;  

    target.setDate(target.getDate() - dayNr + 3);  


    var firstThursday = target.valueOf();  

    target.setMonth(0, 1);  

    if (target.getDay() != 4) {  
    target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);  
    }  

    return 1 + Math.ceil((firstThursday - target) / 604800000); 

i want to calculate the week no. from the given date.....any other solution is also welcome...need it urgently

amit_183
  • 961
  • 3
  • 19
  • 36
  • 2
    possible duplicate of [Show week number with Javascript?](http://stackoverflow.com/questions/7765767/show-week-number-with-javascript) – Wim Ombelets Oct 28 '13 at 08:39
  • @WimOmbelets - the question that you referenced to shows 31st Dec 2013 as 53rd week. But actually its 1st week. Can you please explain? – Praful Bagai Oct 28 '13 at 09:11

2 Answers2

0
function getWeekNumber(d) {
    // Copy date so don't modify original
   var d = new Date(d);
    d.setHours(0,0,0);
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setDate(d.getDate() + 4 - (d.getDay()||7));
    // Get first day of year
    var yearStart = new Date(d.getFullYear(),0,1);
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7)
    // Return array of year and week number
    return [d.getFullYear(), weekNo];
}

Refrence Answer

Community
  • 1
  • 1
0

This code seem to work:

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

Taken from here: http://javascript.about.com/library/blweekyear.htm

Tony Dinh
  • 6,668
  • 5
  • 39
  • 58