Convert java.time.Instant to java.sql.Timestamp and back

Issue: BAEL-2203
This commit is contained in:
yatendragoel 2018-11-05 20:12:08 +05:30 committed by Josh Cummings
parent d83eb69567
commit a8ee73cfc9
1 changed files with 30 additions and 0 deletions

View File

@ -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());
}
}