没有。在javascript中给出一年的一周

时间:2013-10-28 08:38:03

标签: javascript

这是我用来计算周数的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); 

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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