如何将Joda库的日期时间四舍五入到最接近的X分钟?

2022-09-01 12:34:39

如何将图书馆的回合到最近的分钟数?
例如:DateTimeJodaX

X = 10 minutes
Jun 27, 11:32 -> Jun 27, 11:30
Jun 27, 11:33 -> Jun 27, 11:30
Jun 27, 11:34 -> Jun 27, 11:30
Jun 27, 11:35 -> Jun 27, 11:40
Jun 27, 11:36 -> Jun 27, 11:40
Jun 27, 11:37 -> Jun 27, 11:40

答案 1

接受的答案无法正确处理设置了秒或毫秒的日期时间。为了完整起见,下面是一个可以正确处理该问题的版本:

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);
}

答案 2

使用纯日期时间 (Joda) Java 库:

DateTime dt = new DateTime(1385577373517L, DateTimeZone.UTC);
// Prints 2013-11-27T18:36:13.517Z
System.out.println(dt);

// Prints 2013-11-27T18:36:00.000Z (Floor rounded to a minute)
System.out.println(dt.minuteOfDay().roundFloorCopy());

// Prints 2013-11-27T18:30:00.000Z (Rounded to custom minute Window)
int windowMinutes = 10;
System.out.println(
    dt.withMinuteOfHour((dt.getMinuteOfHour() / windowMinutes) * windowMinutes)
        .minuteOfDay().roundFloorCopy()
    );