Rounding a time to its lowest quarter-hour I calculate the lowest quarter-hour using the following code:

public Date getQuarter() {
    Calendar calendar = Calendar.getInstance();
    int mins = calendar.get(Calendar.MINUTE);

    if (mins &lt; 15) {
        mins = 0;
    } else if (mins &lt; 30) {
        mins = 15;
    } else if (mins &lt; 45) {
        mins = 30;
    } else {
        mins = 45;
    }

    calendar.set(Calendar.MINUTE, mins);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}


How can this become better / more elegant?
Java has integer division, so you can divide the minutes by 15 and multiply them again:

int mins = calendar.get(Calendar.MINUTE);
calendar.set(Calendar.MINUTE, mins / 15 * 15);


The division will round the number of 15-minute intervals down to the nearest integer, and multiplying it back gets you the interval you want.



To do this down to the milliseconds, do the same trick but with setTime() directly:

calendar.setTimeInMillis(calendar.getTimeInMillis() / 900000 * 900000);