Date / Time
ZonedDateTime: plusDays と plusHours は夏時間で異なる
夏時間の切替日では、暦日を一つ進めるplusDaysと24時間を足すplusHoursが異なるローカル時刻になります。
SourceDaylightSavingArithmetic.java
Java 21
package examples.datetime;
import java.time.ZonedDateTime;
public final class DaylightSavingArithmetic {
private DaylightSavingArithmetic() {}
public static ZonedDateTime addCalendarDay(ZonedDateTime time) {
return time.plusDays(1);
}
public static ZonedDateTime addTwentyFourHours(ZonedDateTime time) {
return time.plusHours(24);
}
}TestDaylightSavingArithmeticTest.java
Java 21
package examples.datetime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.jupiter.api.Test;
class DaylightSavingArithmeticTest {
@Test
void 夏時間開始日のplusDaysとplusHoursは同じ時刻にならない() {
ZonedDateTime beforeSpringForward =
ZonedDateTime.of(2024, 3, 9, 12, 0, 0, 0, ZoneId.of("America/New_York"));
assertEquals(
"2024-03-10T12:00-04:00[America/New_York]",
DaylightSavingArithmetic.addCalendarDay(beforeSpringForward).toString());
assertEquals(
"2024-03-10T13:00-04:00[America/New_York]",
DaylightSavingArithmetic.addTwentyFourHours(beforeSpringForward).toString());
assertNotEquals(
DaylightSavingArithmetic.addCalendarDay(beforeSpringForward),
DaylightSavingArithmetic.addTwentyFourHours(beforeSpringForward));
}
}01Assertion
このテストで確認できること
- 夏時間開始前日の12時にplusDays(1)すると翌日の12時になる
- 同じ時刻にplusHours(24)すると翌日の13時になる
期限や翌営業日のような暦ベースの要件にはplusDaysを、経過時間の要件にはDurationやplusHoursを使い分けます。
OBSERVED RESULT
expected: plusDays(1) → 12:00
actual: 12:00
expected: plusHours(24) → 13:00
actual: 13:00