|
| 1 | +package com.baeldung.formatinstant; |
| 2 | + |
| 3 | +import static org.assertj.core.api.Assertions.assertThat; |
| 4 | + |
| 5 | +import java.time.Instant; |
| 6 | +import java.time.ZoneId; |
| 7 | +import java.time.format.DateTimeFormatter; |
| 8 | +import java.time.temporal.UnsupportedTemporalTypeException; |
| 9 | + |
| 10 | +import org.joda.time.format.DateTimeFormat; |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +public class FormatInstantUnitTest { |
| 14 | + |
| 15 | + private static final String PATTERN_FORMAT = "dd.MM.yyyy"; |
| 16 | + |
| 17 | + @Test |
| 18 | + public void givenInstant_whenUsingDateTimeFormatter_thenFormat() { |
| 19 | + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT) |
| 20 | + .withZone(ZoneId.systemDefault()); |
| 21 | + |
| 22 | + Instant instant = Instant.parse("2022-02-15T18:35:24.00Z"); |
| 23 | + String formattedInstant = formatter.format(instant); |
| 24 | + |
| 25 | + assertThat(formattedInstant).isEqualTo("15.02.2022"); |
| 26 | + } |
| 27 | + |
| 28 | + @Test(expected = UnsupportedTemporalTypeException.class) |
| 29 | + public void givenInstant_whenNotSpecifyingTimeZone_thenThrowException() { |
| 30 | + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT); |
| 31 | + |
| 32 | + Instant instant = Instant.now(); |
| 33 | + formatter.format(instant); |
| 34 | + } |
| 35 | + |
| 36 | + @Test |
| 37 | + public void givenInstant_whenUsingToString_thenFormat() { |
| 38 | + Instant instant = Instant.ofEpochMilli(1641828224000L); |
| 39 | + String formattedInstant = instant.toString(); |
| 40 | + |
| 41 | + assertThat(formattedInstant).isEqualTo("2022-01-10T15:23:44Z"); |
| 42 | + } |
| 43 | + |
| 44 | + @Test |
| 45 | + public void givenInstant_whenUsingJodaTime_thenFormat() { |
| 46 | + org.joda.time.Instant instant = new org.joda.time.Instant("2022-03-20T10:11:12"); |
| 47 | + |
| 48 | + String formattedInstant = DateTimeFormat.forPattern(PATTERN_FORMAT) |
| 49 | + .print(instant); |
| 50 | + |
| 51 | + assertThat(formattedInstant).isEqualTo("20.03.2022"); |
| 52 | + } |
| 53 | + |
| 54 | +} |
0 commit comments