【问题标题】:Remove timestamp property older than one year from current Time in javascript从javascript中的当前时间删除超过一年的时间戳属性
【发布时间】:2018-03-28 21:03:43
【问题描述】:

我有一个时间戳以毫秒为单位的对象:

const indexes = {
      index1: 1490659200000 // 2017-03-28
      index2: 1490659200000 // 2017-03-28
      index3: 1498608000000 // 2017-06-28
}

如何删除时间戳从当前时间超过一年的索引。 new Date().getTime()-1522269838207。 实际上,循环对象和删除超过 1 年的时间戳的更快方法是什么。也许最好只转换为 yyyy-mm-dd 而不是通过 yyyy, mm-dd 进行比较

Object.keys(indexes).forEach(i => {
   if (indexes[i] < new Date().getTime())
     delete indexes[i];
})

【问题讨论】:

    标签: javascript datetime ecmascript-6 datetime-format


    【解决方案1】:
    const YEAR_IN_MS = 31556952000; // Year in milliseconds
    var now = Data.now(); // current timestamp
    Object.keys(indexes).forEach(i => {
        if (now - indexes[i] >= YEARS_IN_MS) // get difference time and check if greater or equal than year
            delete indexes[i];
    })
    

    【讨论】:

      【解决方案2】:

      这取决于“超过一年”的准确程度。如果我们认为这一年有 365 天,那么:

      const indexes = {
          index1: 1490659200000, // 2017-03-28
          index2: 1490659200000, // 2017-03-28
          index3: 1498608000000 // 2017-06-28
      }
      
      var currentDate = new Date();
      var year = 365 * 24 * 60 * 60 * 1000;
      
      for (var index in indexes) {
          if (indexes[index] < (currentDate - year)) delete indexes[index];
      }
      

      【讨论】:

        【解决方案3】:

        另一种方法是使用函数reduce 以及操作one year - date in object

        这种方法将创建一个日期不超过一年的新数组。

        const indexes = { index1: 1490659200000, index2: 1490659200000,  index3: 1498608000000}
        
        var oneYearAgo = new Date();
        oneYearAgo.setFullYear( oneYearAgo.getFullYear() - 1 );
        
        var result = Object.keys(indexes).reduce((a, c) => {
          if (oneYearAgo.getTime() - indexes[c] > 0) a.push(indexes[c]);
          return a;
        }, [])
        
        console.log(result);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多