|
| 1 | +package com.baeldung.dst; |
| 2 | + |
| 3 | +import static org.assertj.core.api.Assertions.assertThat; |
| 4 | + |
| 5 | +import java.text.ParseException; |
| 6 | +import java.time.LocalDateTime; |
| 7 | +import java.time.ZoneId; |
| 8 | +import java.time.ZonedDateTime; |
| 9 | +import java.time.temporal.ChronoUnit; |
| 10 | +import java.util.TimeZone; |
| 11 | + |
| 12 | +import org.junit.Test; |
| 13 | + |
| 14 | +public class DaylightSavingTimeJavaTimeExamplesTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException { |
| 18 | + ZoneId italianZoneId = ZoneId.of("Europe/Rome"); |
| 19 | + |
| 20 | + LocalDateTime localDateTimeBeforeDST = LocalDateTime.of(2018, 3, 25, 1, 55); |
| 21 | + System.out.println(localDateTimeBeforeDST); |
| 22 | + assertThat(localDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55"); |
| 23 | + |
| 24 | + ZonedDateTime zonedDateTimeBeforeDST = localDateTimeBeforeDST.atZone(italianZoneId); |
| 25 | + prettyPrint(zonedDateTimeBeforeDST); |
| 26 | + assertThat(zonedDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55+01:00[Europe/Rome]"); |
| 27 | + |
| 28 | + ZonedDateTime zonedDateTimeAfterDST = zonedDateTimeBeforeDST.plus(10, ChronoUnit.MINUTES); |
| 29 | + prettyPrint(zonedDateTimeAfterDST); |
| 30 | + assertThat(zonedDateTimeAfterDST.toString()).isEqualTo("2018-03-25T03:05+02:00[Europe/Rome]"); |
| 31 | + |
| 32 | + Long deltaBetweenDatesInMinutes = ChronoUnit.MINUTES.between(zonedDateTimeBeforeDST,zonedDateTimeAfterDST); |
| 33 | + assertThat(deltaBetweenDatesInMinutes).isEqualTo(10); |
| 34 | + |
| 35 | + } |
| 36 | + |
| 37 | + private void prettyPrint(ZonedDateTime zdt) { |
| 38 | + System.out.println(String.format( |
| 39 | + " ZonedDateTime = %s\n" |
| 40 | + + " Zone ID = %s (%s)\n" |
| 41 | + + " RawOffset = %s minutes\n" |
| 42 | + + " -----------------------------------------", |
| 43 | + zdt, zdt.getZone(), zdt.getZone().getId(), zdt.getOffset().getTotalSeconds()/60)); |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + public void whenCounting_ThenPrintDifferencesBetweenAPIs() { |
| 48 | + System.out.println("Total java.time.ZoneId count : " + ZoneId.getAvailableZoneIds().size()); |
| 49 | + System.out.println("Total java.util.TimeZone Id count : " + TimeZone.getAvailableIDs().length); |
| 50 | + } |
| 51 | + |
| 52 | +} |
0 commit comments