日期之间的差异要四舍五入到最接近的分钟。
将date1
,date2
向下或向上四舍五入。返回的结果已经四舍五入到整分钟。我可以修改date1
,date2
。不要修改已经返回的结果
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分钟
答案 0 :(得分:1)
您似乎想要一个从另一个日期减去一个日期并将其差额四舍五入到最接近的分钟的函数。
这不能通过您问题中的单个参数(例如round
函数)来完成;您需要一个将两个日期都作为参数的函数。
我对时刻不太熟悉,但这是一个适用于内置日期的函数。
编辑:根据OP的评论,我更新了该函数以修改d2
而不是返回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);
希望有帮助!
答案 1 :(得分:0)
这可以帮助您将日期四舍五入到最近的分钟:
const date = moment("2019-06-29T21:59:59.000+00:00");
const seconds = date.seconds();
date.add(seconds > 0 && 60 - seconds, 's');
答案 2 :(得分:0)
我们可以使用diff
方法来获取毫秒数,将其转换为分钟,然后将结果取为上限
import moment from 'moment';
let date1 = moment("2019-06-29 21:25:38+00");
console.log(date1)
let date2 = moment("2019-06-29T21:25:40.000+00:00");
console.log(date2)
// get the difference between the moments
const diff = date2.diff(date1);
console.log(diff);
// convert to minutes and ceil
const diffInMinutes = Math.ceil(diff/60000);
console.log(diffInMinutes);