Tom*_*icz 183
如果你已经有了一个Date对象,这很简单:
var coeff = 1000 * 60 * 5;
var date = new Date(); //or use any other date
var rounded = new Date(Math.round(date.getTime() / coeff) * coeff)
Run Code Online (Sandbox Code Playgroud)
使用 ES6 和部分函数,它可以很优雅。选择是否需要四舍五入到最接近或始终向下/向上:
const roundTo = roundTo => x => Math.round(x / roundTo) * roundTo;
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundTo5Minutes = roundTo(1000 * 60 * 5);
const roundDownTo5Minutes = roundDownTo(1000 * 60 * 5);
const roundUpTo5Minutes = roundUpTo(1000 * 60 * 5);
const now = new Date();
const msRound = roundTo5Minutes(now)
const msDown = roundDownTo5Minutes(now)
const msUp = roundUpTo5Minutes(now)
console.log(now);
console.log(new Date(msRound));
console.log(new Date(msDown));
console.log(new Date(msUp));Run Code Online (Sandbox Code Playgroud)
小智 6
我知道现在回答有点晚了,但也许它可以帮助别人。如果您按照以下方式进行会议记录
new Date().getMinutes()
Run Code Online (Sandbox Code Playgroud)
您可以在最后 5 分钟内
new Date().getMinutes() - (new Date().getMinutes()%5)
Run Code Online (Sandbox Code Playgroud)
这是一种将日期对象四舍五入到最接近的x分钟的方法,或者,如果您不提供任何日期,则它将舍入当前时间。
let getRoundedDate = (minutes, d=new Date()) => {
let ms = 1000 * 60 * minutes; // convert minutes to ms
let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);
return roundedDate
}
// USAGE //
// Round existing date to 5 minutes
getRoundedDate(5, new Date()); // 2018-01-26T00:45:00.000Z
// Get current time rounded to 30 minutes
getRoundedDate(30); // 2018-01-26T00:30:00.000Z
Run Code Online (Sandbox Code Playgroud)
Date-fns现在有一个函数可以对日期的分钟进行四舍五入。请参阅https://date-fns.org/v2.21.3/docs/roundToNearestMinutes
const roundToNearestMinutes = require('date-fns/roundToNearestMinutes')
// OR: import roundToNearestMinutes from 'date-fns/roundToNearestMinutes'
console.log(roundToNearestMinutes(new Date(), {nearestTo: 5}));
// e.g. 2021-05-19T22:45:00.000Z
Run Code Online (Sandbox Code Playgroud)