在 javascript 中将 Date()调整到最接近的5分钟

使用 Date()实例,如何将时间调整到最接近的5分钟?

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

48220 次浏览

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

我知道现在回答有点晚了,但也许这能帮到某人。如果你以下列方式记录会议记录

new Date().getMinutes()

你可以把最后5分钟的时间

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

从圆形到最近的 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

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

简而言之:

// 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

有了 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));

可能效率较低,但还有另一种选择:

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

一行解决方案(向上或向下) :

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

Date-fns 现在有了一个函数,它可以在日期上对分钟进行舍入。请参见: “ nofollow norefrer”> 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