0

Hope you can help :-)

Struggling with an unusual rounding issue...

If time is "7:35 AM" the time should be "8:00 AM" - rounded to the nearest 30 minutes going forward...

If time is "7:20 AM" the time should be "7:30 AM"

Any ideas would be appreciated.

I have this but it rounds forwards and backwards. Only need it to go forward:

private DateTime roundDate(final DateTime dateTime, final int minutes) {
    if (minutes < 1 || 60 % minutes != 0) 
    {
        throw new IllegalArgumentException("minutes must be a factor of 60");
    }

    final DateTime hour = dateTime.hourOfDay().roundFloorCopy();
    final long millisSinceHour = new Duration(hour, dateTime).getMillis();
    final int roundedMinutes = ((int) Math.round(millisSinceHour / 60000.0 / minutes)) * minutes;

    System.out.println(hour.plusMinutes(roundedMinutes));

    return hour.plusMinutes(roundedMinutes);
}
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
Amstel Bytes
  • 177
  • 1
  • 8

1 Answers1

0

I would suggest you use the Joda time library. In addition to the cool date helpers it provides, you should find here a snipplet with code that does almost what you need.

Community
  • 1
  • 1
Guy Bouallet
  • 2,099
  • 11
  • 16