Moment:检查日期是否在最近 3 天内

Moment: Check to see if date was within the last 3 days

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

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

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

这是我制作的 link 到 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 );   
    }
}

我猜你想要

function some_within_three_days(store) {
    var three_days_ago = moment().subtract(3, 'days');
    function within_three_days(date) { return moment(date) . isAfter(three_days_ago); }
    return Object.keys(store) . some(within_three_days);
}

或类似的内容,具体取决于您的具体要求。

考虑:

// 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。由于您使用的是整个日期,明确使用中午而不是午夜更安全。