如果前后1分钟或2分钟，如何舍入到最接近的5分钟间隔？

k314159

``````public static Instant toNearest(Duration interval, Instant instant) {
long intervalMillis = interval.toMillis();
long adjustedInstantMillis = (instant.toEpochMilli() + (intervalMillis / 2)) / intervalMillis * intervalMillis;
}

public static LocalDateTime toNearest(Duration interval, LocalDateTime dateTime, ZoneId zoneId) {
ZoneRules zoneRules = zoneId.getRules();
Instant instant = toNearest(interval, dateTime.toInstant(zoneRules.getOffset(dateTime)));
return LocalDateTime.ofInstant(instant, zoneRules.getOffset(instant));
}

public static LocalDateTime toNearest(Duration interval, LocalDateTime dateTime) {
}

@Test
public void toNearestRoundsCorrectly() {
assertThat(toNearest(Duration.ofMinutes(5), LocalDateTime.of(2021, 2, 8, 19, 0, 0)))
.isEqualTo(LocalDateTime.of(2021, 2, 8, 19, 0, 0));
assertThat(toNearest(Duration.ofMinutes(5), LocalDateTime.of(2021, 2, 8, 19, 2, 29, 999999999)))
.isEqualTo(LocalDateTime.of(2021, 2, 8, 19, 0, 0));
assertThat(toNearest(Duration.ofMinutes(5), LocalDateTime.of(2021, 2, 8, 19, 2, 30)))
.isEqualTo(LocalDateTime.of(2021, 2, 8, 19, 5, 0));
assertThat(toNearest(Duration.ofMinutes(5), LocalDateTime.of(2021, 2, 8, 19, 5, 0)))
.isEqualTo(LocalDateTime.of(2021, 2, 8, 19, 5, 0));
}

@Test
public void toNearestTreatsDaylightSavingChangesCorrectly() {
assertThat(toNearest(Duration.ofMinutes(5), LocalDateTime.of(2021,3,27, 23,57,30), ZoneId.of("Europe/London")))
.isEqualTo(LocalDateTime.of(2021,3,28, 0,0,0));
assertThat(toNearest(Duration.ofMinutes(5), LocalDateTime.of(2021,3,28, 0,57,29,999999999), ZoneId.of("Europe/London")))
.isEqualTo(LocalDateTime.of(2021,3,28, 0,55,0));
assertThat(toNearest(Duration.ofMinutes(5), LocalDateTime.of(2021,3,28, 0,57,30), ZoneId.of("Europe/London")))
.isEqualTo(LocalDateTime.of(2021,3,28, 2,0,0));
assertThat(toNearest(Duration.ofMinutes(5), LocalDateTime.of(2021,3,28, 2,5,0), ZoneId.of("Europe/London")))
.isEqualTo(LocalDateTime.of(2021,3,28, 2,5,0));
}
``````

0条评论