【问题标题】:Use moment.js to figure out if a unix timestamp was within the last week使用 moment.js 确定 unix 时间戳是否在上周
【发布时间】:2019-03-06 20:48:49
【问题描述】:

我如何使用 unix 时间戳来确定事件是否在上周?

我试过了

moment().subtract('weeks', 1).unix()<item.start

但它返回了意想不到的结果。非常感谢

编辑:非常感谢这里的问题反馈是我的回应示例

1537858386 1540197758000

【问题讨论】:

  • 您能否详细说明实际结果是什么以及它们与您的预期结果有何不同?
  • 请edit您的问题回答以下问题:这些结果是什么? item.start 的值是多少?我们需要这些答案来帮助您。请阅读minimal reproducible example 了解更多信息,了解我们希望针对此类问题提供哪些信息。
  • “意外结果”,比如“.unix 提供秒数,item.start 包含毫秒数”,也许?
  • 提示一下:moment.js 提供了isSame、isBefore、isAfter、isSameOrBefore、isSameOrAfter 等函数。哪些正在处理这样的事情。查看 moment.js 文档:momentjs.com/docs/#/query

标签: javascript momentjs


【解决方案1】:

正如@be-ndee 所说,这只是毫秒与秒,所以我只是将其编辑为

moment().subtract('weeks', 1).unix()

【讨论】:

    【解决方案2】:

    将使用moment.diff函数

    按照这些步骤进行

    1. 将 unix 时间戳转换为时刻对象
    2. 格式化日期
    3. 使用moment.diff

      function dateDiff (date) {
          // date is unix timestamp date
          let d = moment(date);
      
          if ( d.isValid() ) {
              d.format("YYYY-MM-DD");
      
              // moment() gives current date-time
              return moment().diff(d, 'weeks', true);
              // If past date then result will be positive if future date then negative.
          }
          else 
             return null;
      }
      
      console.log( dateDiff( 1519945200000 ) );  // 30.648079404761905   // 30 weeks ago
      console.log( dateDiff( 1534395200000 ) );  // 6.755883640873016   // 6 weeks ago
      console.log( dateDiff( 1529945200000 ) );  // 14.113687873677248   // 14 weeks ago
      console.log( dateDiff( 1541945200000 ) );  // -5.7275819675925925  // 5 weeks in future
      

    【讨论】:

      【解决方案3】:

      你可以查看date range checking这个答案

      您可以使用moment plugin -> moment-range 之一来处理日期 范围:

       var startDate = new Date(2013, 1, 12)   , endDate   = new Date(2013,
       1, 15)   , date  = new Date(2013, 2, 15)   , range =
       moment().range(startDate, endDate);
      
       range.contains(date); // false
      

      【讨论】:

        【解决方案4】:

        您可以像以前一样创建代表最低有效值的时间点。当你有这个时间点时,你可以用 momentjs 检查给定的日期是否更早。

        const weekAgo = moment().subtract(1, 'weeks') // This is the time to check
        
        const ts = 1519945200000 // any unix timestamp. This is 2018-03-01
        const m1 = moment(ts) // Use a unixtimestamp to create a moment object
        
        const m2 = moment().subtract(8, 'days') // further test data
        const m3 = moment().subtract(6, 'days') // further test data
        
        console.log(weekAgo.isBefore(m1)) // true
        console.log(weekAgo.isBefore(m2)) // true
        console.log(weekAgo.isBefore(m3)) // false
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-24
          • 1970-01-01
          相关资源
          最近更新 更多