gpt4 book ai didi

javascript - 时刻: Check to see if date was within the last 3 days

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

我正在尝试使用 moment 查看对象中的任何日期是否在当前日期的最后 3 天内。

对象的键是日期,但我不确定如何使用 moment 将它们与当前日期进行比较。

编辑:我想查找最近 3 天内的日期的原因是为了获取在该日期范围内找到的问题数。我想我可以做到这一点,只要我能得到一个 bool 标志来确定商店中的对象是否在该日期范围内。

这是我制作的 fiddle 的链接:http://jsfiddle.net/yx22qqvz/

var currentDate = moment().format('YYYY-MM-DD');
var store = {
"2015-05-20": {
"issues": 1
},
"2015-05-18": {
"issues": 2
},
"2015-05-17": {
"issues": 3
},
"2015-05-16": {
"issues": 1
}
};

console.log(currentDate, store);

for (var prop in store) {
if ( store.hasOwnProperty(prop) ) {
console.log(prop);
console.log( moment().diff(currentDate, 'days') > 3 );
}
}

最佳答案

考虑:

// keep this as a moment, and use noon to avoid DST issues
var currentDate = moment().startOf('day').hour(12);

...

// parse the property at noon also
var m = moment(prop + "T12:00:00");

// diff the current date (as a moment), against the specific moment
console.log(currentDate.diff(m, 'days') > 3);

I've also updated your fiddle .

在您的旧代码中,您只是将当前时刻 (moment()) 与 currentDate 进行比较,后者始终为 0 天。您必须解析有问题的属性才能比较那部分数据。

使用中午将避免在某些时区和某些浏览器中,DST 转换当天的午夜被调整回前一天的 23:00 的问题。由于您使用的是整个日期,因此显式使用中午而不是午夜更安全。

关于javascript - 时刻: Check to see if date was within the last 3 days,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30355508/

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