Java 8 LocalDateTime 舍入到下一个 X 分钟



我想将 Java 8 LocalDateTime 转换为最接近的 5 分钟。

例如
1601  ->  1605
1602  ->  1605
1603  ->  1605
1604  ->  1605
1605  ->  1605
1606  ->  1610
1607  ->  1610
1608  ->  1610
1609  ->  1610
1610  ->  1610

我想使用LocalDateTime或Math api的现有功能。有什么建议吗?

您可以使用以下命令舍入到五分钟的下一个倍数:

LocalDateTime dt = …
dt = dt.withSecond(0).withNano(0).plusMinutes((65-dt.getMinute())%5);

您可以使用以下方法重现您的示例

LocalDateTime dt=LocalDateTime.now().withHour(16).withSecond(0).withNano(0);
for(int i=1; i<=10; i++) {
    dt=dt.withMinute(i);
    System.out.printf("%02d%02d -> ", dt.getHour(), dt.getMinute());
    // the rounding step:
    dt=dt.plusMinutes((65-dt.getMinute())%5);
    System.out.printf("%02d%02d%n", dt.getHour(), dt.getMinute());
}

1601 -> 1605
1602 -> 1605
1603 -> 1605
1604 -> 1605
1605 -> 1605
1606 -> 1610
1607 -> 1610
1608 -> 1610
1609 -> 1610
1610 -> 1610

(在这个例子中,我只清除一次秒和纳米,因为它们保持零)。

或者 Holger 的建议,你可以创建一个 TemporalAdjuster ,这将允许你写出类似 date.with(nextOrSameMinutes(5)) 的东西:

public static void main(String[] args) {
  for (int i = 0; i <= 10; i++) {
    LocalDateTime d = LocalDateTime.of(LocalDate.now(), LocalTime.of(16, i, 0));
    LocalDateTime nearest5 = d.with(nextOrSameMinutes(5));
    System.out.println(d.toLocalTime() + " -> " + nearest5.toLocalTime());
  }
}
public static TemporalAdjuster nextOrSameMinutes(int minutes) {
  return temporal -> {
    int minute = temporal.get(ChronoField.MINUTE_OF_HOUR);
    int nearestMinute = (int) Math.ceil(1d * minute / minutes) * minutes;
    int adjustBy = nearestMinute - minute;
    return temporal.plus(adjustBy, ChronoUnit.MINUTES);
  };
}

请注意,这不会截断原始日期的秒/纳秒。如果需要,您可以将调整器的末尾修改为:

if (adjustBy == 0
        && (temporal.get(ChronoField.SECOND_OF_MINUTE) > 0 || temporal.get(ChronoField.NANO_OF_SECOND) > 0)) {
  adjustBy += 5;
}
return temporal.plus(adjustBy, ChronoUnit.MINUTES)
          .with(ChronoField.SECOND_OF_MINUTE, 0)
          .with(ChronoField.NANO_OF_SECOND, 0);

最新更新