如何使用 JavaScript 日期对象四舍五入到最近的小时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7293306/
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 01:39:40  来源:igfitidea点击:

How to round to nearest hour using JavaScript Date Object

javascript

提问by dSquared

I am working on a project that requires a time in the future to be set using the Date object.

我正在处理一个需要使用 Date 对象设置未来时间的项目。

For example:

例如:

futureTime = new Date();
futureTime.setHours(futureTime.getHours()+2);

My questions is; once the future date is set, how can I round to the closest full hour and then set the futureTime var with it?

我的问题是;一旦设置了未来日期,我如何四舍五入到最接近的完整小时,然后用它设置 futureTime 变量?

For example:

例如:

Given 8:55 => var futureTime = 9:00
Given 16:23 => var futureTime = 16:00

Any help would be appreciated!

任何帮助,将不胜感激!

回答by Joe

Round the minutes and then clear the minutes:

四舍五入分钟,然后清除分钟:

var date = new Date(2011,1,1,4,55); // 4:55
roundMinutes(date); // 5:00

function roundMinutes(date) {

    date.setHours(date.getHours() + Math.round(date.getMinutes()/60));
    date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds

    return date;
}

回答by Felix Livni

The other answers ignore seconds and milliseconds components of the date. I would do something like this:

其他答案忽略日期的秒和毫秒部分。我会做这样的事情:

function roundToHour(date) {
  p = 60 * 60 * 1000; // milliseconds in an hour
  return new Date(Math.round(date.getTime() / p ) * p);
}

var date = new Date(2011,1,1,4,55); // 4:55
roundToHour(date); // 5:00

date = new Date(2011,1,1,4,25); // 4:25
roundToHour(date); // 4:00

回答by HBP

A slightly simpler way :

一个稍微简单的方法:

var d = new Date();
d.setMinutes (d.getMinutes() + 30);
d.setMinutes (0);

回答by rlemon

Or you could mix the two for optimal size. http://jsfiddle.net/HkEZ7/

或者您可以将两者混合以获得最佳尺寸。 http://jsfiddle.net/HkEZ7/

function roundMinutes(date) {
    return date.getMinutes() >= 30 ? date.getHours() + 1 : date.getHours();
}

回答by JamesHalsall

Another solution, which is no where near as graceful as IAbstractDownvoteFactory's

另一个解决方案,它远不如 IAbstractDownvoteFactory 的优雅

var d = new Date();
if(d.getMinutes() >= 30) {
   d.setHours(d.getHours() + 1);
}
d.setMinutes(0);

回答by Shubham Rai

Pass any cycle you want in milliseconds to get next cycle example 1 hours

以毫秒为单位传递您想要的任何周期以获得下一个周期示例 1 小时

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(1 * 60 * 60 * 1000)); // 1 hours in milliseconds