我正在使用moment.js,我想获取最近4小时的范围。
如果现在是26/07/2018 02:39
我想获取以下形式的范围数组:
[
{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
。
我该如何减去几个小时,以便为我提供所需的解决方案?
答案 0 :(得分:1)
您可以使用momentjs库中的.startOf()
方法来实现此目的,以获得您的第一次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"
}
]
*/