Skip to content

Commit a8ee73c

Browse files
horizonfrostjzheaux
authored andcommitted
Convert java.time.Instant to java.sql.Timestamp and back
Issue: BAEL-2203
1 parent d83eb69 commit a8ee73c

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.datetime;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import java.sql.Timestamp;
6+
import java.text.DateFormat;
7+
import java.text.SimpleDateFormat;
8+
import java.time.Instant;
9+
import java.time.ZoneId;
10+
import java.util.TimeZone;
11+
12+
import org.junit.Test;
13+
14+
public class ConvertInstantToTimestampUnitTest {
15+
16+
@Test
17+
public void givenInstant_whenConvertedToTimestamp_thenGetTimestampWithSamePointOnTimeline() {
18+
Instant instant = Instant.now();
19+
Timestamp timestamp = Timestamp.from(instant); // same point on the time-line as Instant
20+
assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime());
21+
22+
instant = timestamp.toInstant();
23+
assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime());
24+
25+
DateFormat df = DateFormat.getDateTimeInstance();
26+
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
27+
df.setTimeZone(TimeZone.getTimeZone("UTC"));
28+
assertThat(instant.toString()).isEqualTo(df.format(timestamp).toString());
29+
}
30+
}

0 commit comments

Comments
 (0)