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

2
  • 2
    possible duplicate of Show week number with Javascript? Commented Oct 28, 2013 at 8:39
  • @WimOmbelets - the question that you referenced to shows 31st Dec 2013 as 53rd week. But actually its 1st week. Can you please explain? Commented Oct 28, 2013 at 9:11

2 Answers 2

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

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

2 Comments

can u tell what is d?
@amit_183 d is the date
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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.