首页 > 解决方案 > Moment.js 获取最近 4 小时的范围

问题描述

我正在使用 moment.js,我想获得最后 4 小时的范围。

例子

如果是现在26/07/2018 02:39

我想以 of 形式获得一系列范围:

[
  {from:'26/07/2018 02:00' , to:'26/07/2018 02:39'},
  {from:'26/07/2018 01:00', to:'26/07/2018 02:00'},
  {from:'26/07/2018 00:00', to:'26/07/2018 01:00'},
  {from: '25/07/2018 23:00', to:'26/07/2018 00:00'}   
] 

以上只是我希望过去 4 小时的持续时间的一个示例。

到目前为止,我已经尝试过:

let current = moment();
//here am stuck on how to substract the above

它应该是这样的:

moment().substract(1, 'hours') 

但是,上面是减去一小时02:39并将返回01:39。我该如何减少小时数,以便为我提供所需的解决方案?

标签: javascriptmomentjs

解决方案


您可以使用.startOf()momentjs 库中的方法来实现这一点,以获得您的第from一次。

从那里,您可以使用该.subtract()方法在您需要的范围内减少时间。还要注意使用.clone(), 以确保

例如,像这样的函数将生成您需要的时间数组:

function getFourTimeRanges( timestampString ) {

    // Parse first "to" time for range, from input timestamp string 
    // (based on format in your question)
    var firstTo = moment(timestampString , 'DD-MM-YYY HH:mm');

    // Calculate first "from" time using startOf to "round down" to 
    // start of current hour
    var firstFrom = firstTo .clone().startOf('hour');

    var format = 'DD/MM/YYYY HH:mm'

    // Add first formatted range into timeRanges array    
    var timeRanges = [{ 
        from : firstFrom.format(format), 
        to : firstTo.format(format) 
    }]

    // Iterate three times to compute and add remaining time ranges
    // to timeRanges result array
    for(var i = 0; i < 3; i++) {

        // Calculate "from" and "to" times for each of the remaining 
        // times ranges we want to calculate
        var from = firstFrom.clone().subtract(i + 1, 'hours').startOf('hour')
        var to = firstFrom.clone().subtract(i, 'hours').startOf('hour')

        // Add formatted time range to timeRanges array
        timeRanges.push({ 
            from : from.format(format),
            to : to.format(format)
         })
    }

    return timeRanges
}

// Then use method as follows

getFourTimeRanges('26/07/2018 02:39')

/*
[
  {
    "from": "26/07/0018 02:00",
    "to": "26/07/0018 02:39"
  },
  {
    "from": "26/07/0018 01:00",
    "to": "26/07/0018 02:00"
  },
  {
    "from": "26/07/0018 00:00",
    "to": "26/07/0018 01:00"
  },
  {
    "from": "25/07/0018 23:00",
    "to": "26/07/0018 00:00"
  }
]
*/

推荐阅读