2

这是我用来计算周数的 th javscript 代码。从给定的日期......但我得到的输出不正确

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

我想计算周数。从给定日期起......任何其他解决方案也受到欢迎......迫切需要它

4

2 回答 2

0

这段代码似乎工作:

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

取自这里:http: //javascript.about.com/library/blweekyear.htm

于 2013-10-28T08:42:05.467 回答
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];
}

参考答案

于 2013-10-28T08:40:07.770 回答