如果时间是10:36,我想把时间缩短到10:30。如果时间是1050我想把时间缩短到10:45。等...我不知道该怎么做。有什么想法吗?
答案 0 :(得分:1)
这个怎么样?
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)
无效。)
答案 1 :(得分:0)
感谢您的回复。决定走这条路而不介绍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());
答案 2 :(得分:0)
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等)时才有效。