gpt4 book ai didi

javascript - 日期之间的差异,四舍五入到最近的分钟

转载 作者:行者123 更新时间:2023-11-30 19:26:46 24 4
gpt4 key购买 nike

日期之间的差异要四舍五入到最近的分钟。date1date2 向下或向上舍入。返回的结果已经四舍五入到整分钟。我可以修改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 分钟

最佳答案

您似乎想要一个函数,将一个日期减去另一个日期并将差值四舍五入到最接近的分钟。

这不能通过问题中的 round 函数这样的单个参数来完成;您需要一个将两个日期都作为参数的函数。

我对 moment 不太熟悉,但这里有一个应该适用于内置日期的函数。

编辑:根据 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);

希望对您有所帮助!

关于javascript - 日期之间的差异,四舍五入到最近的分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com