在 javascript 中将 Date() 舍入到最接近的 5 分钟

Round a Date() to the nearest 5 minutes in javascript

本文关键字:最接近 分钟 舍入 javascript 中将 Date      更新时间:2023-09-26

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

例如:如果是下午 4:

47,则会将时间设置为下午 4:45。

如果您已经有一个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)

舍入到最接近的 x 分钟

这是一个将日期对象舍入到最接近的 x 分钟的方法,或者如果您不给它任何日期,它将舍入当前时间。

function 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

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

我知道

现在回答有点晚了,但也许它可以帮助某人。如果您按以下方式获取会议记录

new Date().getMinutes()

您可以通过以下方式使用最后 5 分钟

new Date().getMinutes() - (new Date().getMinutes()%5)

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

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

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

使用此方法使用纯 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

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

总之:

// 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
可以使用

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

单行解决方案(向上或向下舍入):

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