gpt4 book ai didi

javascript - “几周前”的剧本不占多年

转载 作者:行者123 更新时间:2023-11-30 17:48:00 24 4
gpt4 key购买 nike

标题几乎已经说明了,我的脚本从一个日期算起多少周前没有计算年份,并且返回了一个错误的值?

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

最佳答案

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

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 .

关于javascript - “几周前”的剧本不占多年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19711826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com