日期之间的差异,将结果四舍五入到最接近的分钟 [英] Difference between dates, rounded result to nearest minute
问题描述
日期之间的差异要四舍五入到最接近的分钟.向下或向上四舍五入 date1
, date2
.返回的结果已经四舍五入到整分钟.我可以修改 date1
, date2
.不要修改已经返回的结果
The difference between dates wants to round to the nearest minute.
Round date1
,date2
down or up. The returned result is already rounded up to the full minute. I can modify date1
,date2
. Do not modify the result already returned
date2- date1
此处的代码: https://stackblitz.com/edit/react-azau4g
示例:
第一步
this.state = {
date1: "2019-06-29 21:25:38+00",
date2: "2019-06-29T21:25:40.000+00:00"
}
round = (item) => {
var m = moment(item);
var roundUp = (m.second() || m.millisecond() ? m.add(1, 'minute').startOf('minute') : m.startOf('minute')).toISOString();
return roundUp;
}
differentTime = {
date1: this.state.date1.toISOString(),
date2: this.round(this.state.date2) //return "2019-06-29T21:26:00.000+00:00"
}
第二步
预期效果:
data2
- data1
= 1分钟
示例2
this.state = {
date1: "2019-06-29 21:25:01+00",
date2: "2019-06-29T21:27:20.000+00:00"
}
differentTime2 = {
date1: this.state.date1.toISOString(),
date2: this.round(this.state.date2) //return "2019-06-29T21:28:00.000+00:00"
}
预期效果:
date2
- date1
= 3分钟
推荐答案
您似乎想要一个从另一个日期减去一个日期并将其差额四舍五入到最接近的分钟的函数.
It looks like you want a function that subtracts one date from another and round the difference to the nearest minute.
这不能通过单个参数(例如问题中的 round
函数)来完成;您需要一个将两个日期都作为参数的函数.
This can't be done with a single argument like the round
function in your question; you need a function that takes both dates as arguments.
我对时刻不太熟悉,但这是一个适用于内置Dates的函数.
I'm not too familiar with moment, but here's a function that should work for built-in Dates.
根据OP的评论,我更新了该函数以修改 d2
而不是返回diff.
Per OP's comments, I've updated the function to modify d2
rather than returning diff.
MS_IN_MINUTES = 60000;
roundAway = (d1, d2) => {
let diff = d2 - d1 // Difference in milliseconds (+ or -)
let positive = diff > 0 // Whether we should add later
diff = Math.abs(diff) // Difference in milliseconds (+)
diff = diff / MS_IN_MINUTES // Difference in minutes (not rounded)
diff = Math.ceil(diff) // Difference in minutes (rounded up)
let roundedAway = d1.getTime()
if (positive) {
roundedAway += diff * MS_IN_MINUTES
}
else {
roundedAway -= diff * MS_IN_MINUTES
}
d2.setTime(roundedAway)
}
let date1 = new Date("2019-06-29 21:25:38+00");
console.log('date1:', date1)
let date2 = new Date("2019-06-29T21:25:40.000+00:00");
console.log('date2:', date2)
let date3 = new Date("2019-06-29T21:24:36.000+00:00");
console.log('date3:', date3)
console.log('Unchanged date1:', date1);
roundAway(date1, date2);
console.log('Rounded date2:', date2);
roundAway(date1, date3);
console.log('Rounded date3:', date3);
希望有帮助!
这篇关于日期之间的差异,将结果四舍五入到最接近的分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!