如何在java中将时间四舍五入到最近的四分之一小时? [英] How to round time to the nearest quarter hour in java?
本文介绍了如何在java中将时间四舍五入到最近的四分之一小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于今天的时间,例如下午 2:24,我如何将它舍入到下午 2:30?
Given today's time e.g. 2:24PM, how do I get it to round to 2:30PM?
同样,如果时间是下午 2 点 17 分,我如何将它舍入到下午 2 点 15 分?
Similarly if the time was 2:17PM, how do I get it to round to 2:15PM?
推荐答案
四舍五入
您需要使用模数来截断一刻钟:
Rounding
You will need to use modulo to truncate the quarter hour:
Date whateverDateYouWant = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(whateverDateYouWant);
int unroundedMinutes = calendar.get(Calendar.MINUTE);
int mod = unroundedMinutes % 15;
calendar.add(Calendar.MINUTE, mod < 8 ? -mod : (15-mod));
正如EJP所指出的,这也可以(替换最后一行,仅当日历为宽松):
As pointed out by EJP, this is also OK (replacement for the last line, only valid if the calendar is lenient):
calendar.set(Calendar.MINUTE, unroundedMinutes + mod);
<小时>
改进
如果您想准确,您还必须截断较小的字段:
Improvements
If you want to be exact, you will also have to truncate the smaller fields:
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
您也可以使用 DateUtils.truncate() 来自 Apache Commons/Langa> 这样做:
You can also use DateUtils.truncate() from Apache Commons / Lang to do this:
calendar = DateUtils.truncate(calendar, Calendar.MINUTE);
这篇关于如何在java中将时间四舍五入到最近的四分之一小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文