From a8ee73cfc9d1e0d6cf4e092e79b95fc1d12ec74d Mon Sep 17 00:00:00 2001 From: yatendragoel Date: Mon, 5 Nov 2018 20:12:08 +0530 Subject: [PATCH] Convert java.time.Instant to java.sql.Timestamp and back Issue: BAEL-2203 --- .../ConvertInstantToTimestampUnitTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 java-dates/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java diff --git a/java-dates/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java b/java-dates/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java new file mode 100644 index 0000000000..3ba01a591a --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/datetime/ConvertInstantToTimestampUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.datetime; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Timestamp; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.ZoneId; +import java.util.TimeZone; + +import org.junit.Test; + +public class ConvertInstantToTimestampUnitTest { + + @Test + public void givenInstant_whenConvertedToTimestamp_thenGetTimestampWithSamePointOnTimeline() { + Instant instant = Instant.now(); + Timestamp timestamp = Timestamp.from(instant); // same point on the time-line as Instant + assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime()); + + instant = timestamp.toInstant(); + assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime()); + + DateFormat df = DateFormat.getDateTimeInstance(); + df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + assertThat(instant.toString()).isEqualTo(df.format(timestamp).toString()); + } +}