javascript - 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
。我该如何减少小时数,以便为我提供所需的解决方案?
解决方案
您可以使用.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"
}
]
*/
推荐阅读
- vba - 如何单击具有类和为特定按钮提供的 ID 的按钮
- android-studio - 无法在最新的 android 版本上创建 AVD
- c# - 使用 PdfSharp 将文档链接添加到现有 Pdf 文件
- javascript - 尝试返回从返回的 mysql 查询的 foreach 循环构建的数组
- wordpress - 为什么“header.php”中的图像只显示在一页中?
- javascript - JavaScript 模块在 Edge 浏览器中不起作用
- ios - 你可以在 Xcode 中编写 JavaScript/React-Native 代码吗?
- cobol - “录音”无效。文件采用“V”的“记录模式”
- javascript - 按两个不同的属性javascript对项目进行排序
- java - maven 测试因空指针而失败,但junit 5 ok