问题
If the time is 10:36 I would like to round the time down to 10:30. If the time is 1050 I would like to round the time down to 10:45. etc... I am not sure how to do this. Any ideas?
回答1:
How about this?
public static LocalTime roundToQuarterHour(LocalTime time) {
int oldMinute = time.getMinuteOfHour();
int newMinute = 15 * (int) Math.round(oldMinute / 15.0);
return time.plusMinutes(newMinute - oldMinute);
}
(It may seem slightly overcomplicated since there's a withMinuteOfHour
method, but keep in mind that we might round to 60, and withMinuteOfHour(60)
is invalid.)
回答2:
Thanks for the responses. Decided to go this route and not introduce JodaTime. As found in this answer 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());
回答3:
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);
}
Only works when toMinuteInterval is a factor of 60 (eg 10, 15, 30 etc).
来源:https://stackoverflow.com/questions/22445573/jodatime-rounding-down-to-nearest-quarter-of-hour