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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10789384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:56:14  来源:igfitidea点击:

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

javascript

提问by Jick Lee

Using a Date()instance, how might I round a time to the nearest five minutes?

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

For example: if it's 4:47 p.m. it'll set the time to 4:45 p.m.

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

回答by Tomasz Nurkiewicz

That's pretty simple if you already have a Dateobject:

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

回答by joshuakcockrell

Round to nearest x minutes

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

Here is a method that will round a date object to the nearest x minutes, or if you don't give it any date it will round the current time.

这是一种将日期对象舍入到最接近的 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

回答by user3767296

I know it is bit late for answer but maybe it can help someone. If you take the minutes by the following

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

new Date().getMinutes()

you can take the last 5 minutes by

你可以用最后 5 分钟

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

回答by peter.bartos

With ES6 and partial functions it can be elegant:

使用 ES6 和部分函数,​​它可以很优雅:

const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundDownTo5Minutes = roundDownTo(1000*60*5);

const ms = roundDownTo5Minutes(new Date())
console.log(new Date(ms)); // Wed Jun 05 2019 15:55:00 GMT+0200

回答by Shubham Rai

Use this method to get the next 5 minute cycle using pure JS

使用这个方法,使用纯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

回答by Malvineous

Probably less efficient but here's another alternative:

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

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
Current timestamp: 2019-10-22T09:47:17.989Z
Rounded timestamp: 2019-10-22T09:45:00.000Z

回答by Vladimir Semashkin

recently found a very efficient way to round off the date to a timeframe

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

in short:

简而言之:

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

I bit of my testing in LINQPad

我在 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();

output:

输出:

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

回答by Danny Hurlburt

There is an NPM package@qc/date-roundthat can be used. Given that you have a Dateinstance to be rounded

有一个可以使用的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)

Then you can use date-fnsto format the date

然后你可以使用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