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?
Asked
Active
Viewed 3,113 times
3
-
Devise the mid point between the values (1045 and 1100) and determine if the current values falls closer to 1045 or 1100, adjust accordingly... – MadProgrammer Mar 17 '14 at 01:42
3 Answers
2
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.)

Daniel Lubarov
- 7,796
- 1
- 37
- 56
-
1It seems he only wanted to round down so you should actually do this with `Math.floor`. In that case you don't have the problem of the 60 minutes. – Didier L Mar 17 '14 at 14:40
-
Thank you for the hints without java.time. If you want to **round up** to the nearest Quarter, then you could use `Math.floor` in Combination with your code: `int newMinute = 15 * (int) Math.floor(oldMinute / 15.0);` and `return time.plusMinutes(newMinute - oldMinute +15)` – leole Dec 18 '19 at 08:21
-
0
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());
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);
}
Only works when toMinuteInterval is a factor of 60 (eg 10, 15, 30 etc).

bsa
- 2,671
- 21
- 31