'Weeks Ago'剧本不考虑多年

时间:2013-10-31 16:26:07

标签: javascript date

标题几乎是这样说的,我的剧本是从几个星期前的一个日期以来不是会计年度,并且返回一个不好的价值?

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

1 个答案:

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

披露:这很重要基于this SO answer