75

使用Date()实例,我如何将时间四舍五入到最接近的五分钟?

例如:如果是下午 4:47,它会将时间设置为下午 4:45

4

10 回答 10

248

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)
于 2012-05-28T19:13:18.203 回答
18

四舍五入到最接近的 x 分钟

这是一种将日期对象舍入到最接近的 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
于 2018-01-26T00:28:53.080 回答
13

使用 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));

于 2019-06-05T13:53:21.280 回答
4

我知道回答有点晚了,但也许它可以帮助某人。如果您按以下方式记录

new Date().getMinutes()

你可以在最后 5 分钟

new Date().getMinutes() - (new Date().getMinutes()%5)
于 2014-11-16T12:25:14.177 回答
3

可能效率较低,但这是另一种选择:

debug('Current timestamp:', timestamp);

timestamp.setMilliseconds(0);
timestamp.setSeconds(0);
timestamp.setMinutes(Math.round(timestamp.getMinutes() / 5) * 5);

debug('Rounded timestamp:', timestamp);
Current timestamp: 2019-10-22T09:47:17.989Z
Rounded timestamp: 2019-10-22T09:45:00.000Z
于 2019-10-22T09:49:40.960 回答
1

Date-fns现在有一个函数,可以对日期进行四舍五入。见https://date-fns.org/v2.21.3/docs/roundToNearestMinutes

const roundToNearestMinutes = require('date-fns/roundToNearestMinutes')
console.log(roundToNearestMinutes(new Date(), {nearestTo: 5}));
// e.g. 2021-05-19T22:45:00.000Z
于 2021-05-19T22:47:04.277 回答
1

使用此方法获取下一个使用纯JS的5分钟循环

function calculateNextCycle(interval) {
    const timeStampCurrentOrOldDate = Date.now();
    const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
    const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
    const mod = Math.ceil(timeDiff / interval);
    return new Date(timeStampStartOfDay + (mod * interval));
}

console.log(calculateNextCycle(5 * 60 * 1000)); // pass in milliseconds

于 2020-05-06T17:06:24.663 回答
0

一条线解决方案(向上或向下舍入):

const fixedTime = (isRoundUp ? Math.ceil : Math.floor)(time / 60_000 / minutesRange)) * 60_000 * minutesRange;

// minutesRange: number -> 1, 5, 15, 30, etc // minutes
// isRoundUp: boolean
// time: number // millis
于 2021-02-08T22:05:42.193 回答
0

有一个NPM 包 @qc/date-round可以使用。鉴于您有一个Date要四舍五入的实例

import { round } from '@qc/date-round'

const dateIn = ...; // The date to be rounded
const interval = 5 * 60 * 1000; // 5 minutes
const dateOut = round(dateIn, interval)

然后你可以使用date-fns格式化日期

import format from 'date-fns/format';

console.log(format(dateOut, 'HH:mm')) // 24-hr
console.log(format(dateOut, 'hh:mm a')) // 12-hr
于 2018-11-04T17:48:30.040 回答
0

最近发现了一种将日期四舍五入到时间范围的非常有效的方法

简而言之:

// minutes
var tf = 15; // 5,10,13,15, 60, - what ever you want
var dt = DateTime.UtcNow;
var minues = dt.TimeOfDay.TotalMinutes; // use TotalMinutes, TotalSecibds, TotalMillisecons  and etc
var roundedMinutes = (minues - (minues%tf));
var roundedDate = dt.Date.AddMinutes(a);

我在 LINQPad 中进行了一些测试

// minutes
var tf = 15; // 5,10,13,15, 60, - what ever you want
var dt = DateTime.UtcNow;
var minues = dt.TimeOfDay.TotalMinutes;
dt.Dump();
minues.Dump();
(ms%tf).Dump();
var a = (minues - (minues%tf));
a.Dump();
dt.Date.AddMinutes(a).Dump();

输出:

13.07.2018 7:43:58 - current date
463,981443103333 - total mins
13,9814431033333 - rest
450 - rounded minutes value
13.07.2018 7:30:00 - rounded date
于 2018-07-13T07:48:48.067 回答