[英]Moment.js get the last 4 hour ranges
我正在使用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
减去1小时后将返回01:39
。 我如何减去小时数,以便它能给我所需的解决方案?
您可以使用实现这个.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"
}
]
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.