1

标题几乎说明了这一点,我从某个日期开始几周前的脚本没有考虑到这一年,并且返回了一个错误的值?

var today = new Date();
var timestamp = new Date($(this).attr('timestamp') * 1000);

Date.prototype.getWeeks = function()
{
    var jan = new Date(this.getFullYear(), 0, 1);
    var now = new Date(this.getFullYear(),this.getMonth(),this.getDate());
    var doy = ((now - jan + 1) / 86400000);
    return Math.ceil(doy / 7)
};

console.log('Today: ' + today);                 // Date {Thu Oct 31 2013 09:21:19 GMT-0700 (PDT)}
console.log('PastT: ' + timestamp);             // Date {Fri Nov 20 2009 17:00:00 GMT-0800 (PST)}

console.log('Today: ' + today.getWeeks());      // 44 <-- Should be zero
console.log('PastT: ' + timestamp.getWeeks());  // 47 <-- Not accounting for the Years

console.log('Since: ' + (today.getWeeks() - timestamp.getWeeks())); // time ago = -3
4

1 回答 1

2

您可以比较日期,然后将差异(以毫秒为单位)转换为周:

function dateDiffInWeeks(a,b) {
    var _MS_PER_WEEK = 1000 * 60 * 60 * 24 * 7;
    var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
    var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
    return Math.floor((utc2 - utc1) / _MS_PER_WEEK);
}

var today = new Date();
var anotherDay = new Date("Fri Nov 20 2009");

alert(dateDiffInWeeks(today,anotherDay));

JSFiddle

披露:这是非常基于这个 SO answer的。

于 2013-10-31T16:42:45.040 回答