【发布时间】:2014-03-17 01:40:49
【问题描述】:
如果时间是 10:36,我想将时间四舍五入到 10:30。如果时间是 1050,我想将时间四舍五入到 10:45。等等......我不知道该怎么做。有什么想法吗?
【问题讨论】:
-
确定值(1045 和 1100)之间的中点,并确定当前值是否接近 1045 或 1100,相应调整...
如果时间是 10:36,我想将时间四舍五入到 10:30。如果时间是 1050,我想将时间四舍五入到 10:45。等等......我不知道该怎么做。有什么想法吗?
【问题讨论】:
这个怎么样?
public static LocalTime roundToQuarterHour(LocalTime time) {
int oldMinute = time.getMinuteOfHour();
int newMinute = 15 * (int) Math.round(oldMinute / 15.0);
return time.plusMinutes(newMinute - oldMinute);
}
(由于有 withMinuteOfHour 方法,这可能看起来有点过于复杂,但请记住,我们可能会舍入到 60,而 withMinuteOfHour(60) 是无效的。)
【讨论】:
Math.floor 来做这个。在这种情况下,您就没有 60 分钟的问题。
Math.floor 与您的代码组合使用:int newMinute = 15 * (int) Math.floor(oldMinute / 15.0); 和 return time.plusMinutes(newMinute - oldMinute +15)
感谢您的回复。决定走这条路,不介绍 JodaTime。正如在这个答案中找到的How to round time to the nearest quarter hour in java?
long timeMs = System.currentTimeMillis();
long roundedtimeMs = Math.round( (double)( (double)timeMs/(double)(15*60*1000) ) ) * (15*60*1000);
Date myDt = new Date(roundedtimeMs);
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDt);
if(calendar.before(new Date())) {
calendar.add(Calendar.MINUTE, -15);
}
System.out.println(calendar.getTime());
【讨论】:
public static LocalTime roundDown(LocalTime time, int toMinuteInterval) {
int slotNo = (int)(time.getMillisOfDay() / ((double)toMinuteInterval * 60 * 1000));
int slotsPerHour = 60 / toMinuteInterval;
int h = slotNo / slotsPerHour;
int m = toMinuteInterval * (slotNo % slotsPerHour);
return new LocalTime(h, m);
}
仅当 toMinuteInterval 为 60 倍(例如 10、15、30 等)时才有效。
【讨论】: