How to round DateTime of Joda library to the nearest X minutes?

后端 未结 6 1533
[愿得一人]
[愿得一人] 2020-12-28 14:42

How to round DateTime of Joda library to the nearest X minutes ?
For example:

X = 10 minutes
Jun 27, 11:32 -> Jun 27, 11         


        
6条回答
  •  被撕碎了的回忆
    2020-12-28 15:20

    The accepted answer doesn't correctly handle datetimes that have seconds or milliseconds set. For completeness, here's a version that does handle that correctly:

    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;
        return hour.plusMinutes(roundedMinutes);
    }
    

提交回复
热议问题