如何在java中将时间缩短到最接近的四分之一小时? [英] How to round time to the nearest quarter hour in java?

查看:113
本文介绍了如何在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轮: 15PM?

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所指出的,这也没关系(替换最后一行,只有在日历是 lenient ):

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() =http://commons.apache.org/lang =noreferrer> Apache Commons / Lang 这样做:

You can also use DateUtils.truncate() from Apache Commons / Lang to do this:

calendar = DateUtils.truncate(calendar, Calendar.MINUTE);

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

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