时刻:检查日期是否在过去3天内

时间:2015-05-20 16:32:15

标签: javascript momentjs

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

对象的键是日期,但我不知道如何使用时刻将它们与当前日期进行比较。

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

这是我制作小提琴的链接: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 );   
    }
}

2 个答案:

答案 0 :(得分:2)

考虑:

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

答案 1 :(得分:1)

我猜你想要

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);
}

或类似的东西,取决于您的确切要求。

相关问题