如何在 JavaScript 中将时间四舍五入到最近的四分之一小时? [英] How to round time to the nearest quarter hour in JavaScript?

查看:17
本文介绍了如何在 JavaScript 中将时间四舍五入到最近的四分之一小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

Given time: 08:22 => Rounded to: 08:15

Given time: 08:23 => Rounded to: 08:30

应该很简单.但是我所能产生的只是冗长的,不是很好的代码来解决这个问题.我的脑子一片空白.

Should be pretty simple. But all I was able to produce is lengthy, not very good code to solve the issue. My mind's just gone blank.

问候

推荐答案

鉴于变量中有小时和分钟(如果没有,则无论如何都可以通过使用从 Date 实例中获取它们Date 实例 函数):

Given that you have hours and minutes in variables (if you don't you can get them from the Date instance anyway by using Date instance functions):

var m = (parseInt((minutes + 7.5)/15) * 15) % 60;
var h = minutes > 52 ? (hours === 23 ? 0 : ++hours) : hours;

分钟也可以使用Math.round()来计算:

minutes can as well be calculated by using Math.round():

var m = (Math.round(minutes/15) * 15) % 60;

或者在没有任何函数的更复杂的 javascript 表达式中进行:

or doing it in a more javascript-sophisticated expression without any functions:

var m = (((minutes + 7.5)/15 | 0) * 15) % 60;
var h = ((((minutes/105) + .5) | 0) + hours) % 24;

您可以检查 jsPerf 测试,该测试显示 Math.round() 是三个中最慢的,而主要是最后一个最快,因为它只是一个没有任何函数调用的表达式(没有函数调用开销,即堆栈操作,尽管在 Javascript VM 中可能会以不同的方式处理本机函数).//----

You can check the jsPerf test that shows Math.round() is the slowest of the three while mainly the last one being the fastest as it's just an expression without any function calls (no function call overhead i.e. stack manipulation, although native functions may be treated differently in Javascript VM). //----

这篇关于如何在 JavaScript 中将时间四舍五入到最近的四分之一小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆