public static ZonedDateTime round(ZonedDateTime input, TemporalField roundTo, int roundIncrement) {
/* Extract the field being rounded. */
int field = input.get(roundTo);
/* Distance from previous floor. */
int r = field % roundIncrement;
/* Find floor and ceiling. Truncate values to base unit of field. */
ZonedDateTime ceiling =
input.plus(roundIncrement - r, roundTo.getBaseUnit())
.truncatedTo(roundTo.getBaseUnit());
ZonedDateTime floor =
input.plus(-r, roundTo.getBaseUnit())
.truncatedTo(roundTo.getBaseUnit());
/*
* Do a half-up rounding.
*
* If (input - floor) < (ceiling - input)
* (i.e. floor is closer to input than ceiling)
* then return floor, otherwise return ceiling.
*/
return Duration.between(floor, input).compareTo(Duration.between(input, ceiling)) < 0 ? floor : ceiling;
}
资料来源:我自己
# 4 楼答案
四舍五入
您需要使用模来截断四分之一小时:
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));
# 1 楼答案
很简单,把1970年以来四分之一的数字取为两倍,四舍五入,再乘以15分钟:
用它设置日期或日历对象
# 2 楼答案
如果您只想进行取整,这是一个更可读的版本,使用Java Time API:
输出:
2016-11-04T10:58:10.228
2016-11-04T10:45:00
# 3 楼答案
Java8的注释实现。接受任意舍入单位和增量:
资料来源:我自己
# 4 楼答案
四舍五入
您需要使用模来截断四分之一小时:
正如EJP所指出的,这也是可以的(替换最后一行,仅当日历为lenient时有效):
改进
如果希望精确,还必须截断较小的字段:
您还可以使用DateUtils.truncate()from Apache Commons / Lang来执行以下操作: