From 7b44b2759fc59b2009d6397d5d87809a49e6ae6e Mon Sep 17 00:00:00 2001 From: ACHRAF TAITAI <43656331+achraftt@users.noreply.github.com> Date: Sun, 16 Oct 2022 20:09:54 +0200 Subject: [PATCH] BAEL-5791: Convert String to Instant (#12876) --- .../StringToInstantConverterUnitTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/instant/StringToInstantConverterUnitTest.java diff --git a/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/instant/StringToInstantConverterUnitTest.java b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/instant/StringToInstantConverterUnitTest.java new file mode 100644 index 0000000000..a3732bf7da --- /dev/null +++ b/core-java-modules/core-java-datetime-string/src/test/java/com/baeldung/instant/StringToInstantConverterUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.instant; + +import org.junit.Test; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Locale; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StringToInstantConverterUnitTest { + String stringDate = "09:15:30 PM, Sun 10/09/2022"; + String pattern = "hh:mm:ss a, EEE M/d/uuuu"; + + @Test public void givenStringTimeStamp_whenConvertingWithInstantUsingTimeZone_thenConvertToInstant() { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern, Locale.US); + LocalDateTime localDateTime = LocalDateTime.parse(stringDate, dateTimeFormatter); + ZoneId zoneId = ZoneId.of("America/Chicago"); + ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId); + Instant instant = zonedDateTime.toInstant(); + assertThat(instant.toString()).isEqualTo("2022-10-10T02:15:30Z"); + } + + @Test public void givenStringTimeStamp_whenConvertingWithLocalDateTime_thenConvertToInstant() { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern, Locale.US); + LocalDateTime localDateTime = LocalDateTime.parse(stringDate, dateTimeFormatter); + assertThat(localDateTime.toString()).isEqualTo("2022-10-09T21:15:30"); + } +} \ No newline at end of file