Both java.time.Instant and java.sql.Timestamp classes represent a point on the timeline in UTC. In other words, they represent the number of nanoseconds since the Java epoch.
In this quick tutorial, we'll convert one to the other by using built-in Java methods.
2. Converting Instant to Timestamp and Back
We can use Timestamp.from() to convert Instants into Timestamps:
Instant instant = Instant.now();
Timestamp timestamp = Timestamp.from(instant);
And vice-versa, we can use Timestamp.toInstant() to convert Timestamps into Instants:
instant = timestamp.toInstant();
Either way, both the Instant and Timestamp represents the same point on the timeline.
Next, let's have a look at the interaction between the two classes and the timezone.
3. toString() Method Differences
Invoking toString() on Instant and Timestamp behaves differently with respect to timezone. Instant.toString() returns the time in UTC timezone. On the other hand, Timezone.toString() returns the time in the local machine timezone.
Let's see what we get when calling toString() on instant and timestamp respectively:
Instant (in UTC): 2018-10-18T00:00:57.907Z
Timestamp (in GMT +05:30): 2018-10-18 05:30:57.907
Here, timestamp.toString() resulted in a time which is 5 hours 30 minutes after the time returned by the instant.toString(). This is because the local machine's timezone is at GMT +5:30 timezone.
The output of the toString() method is different, but both the timestamp and instant represent the same point on the timeline.
We can also verify this by converting the Timestamp to the UTC time zone:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter = formatter.withZone(TimeZone.getTimeZone("UTC").toZoneId());
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
In this quick tutorial, we saw how to convert between java.time.Instant and java.sql.Timestamp classes in Java using built-in methods.
We also had a look at how the time zone affects how the output changes.
And, as always, the complete code examples are available over on GitHub.
res – REST with Spring (eBook) (everywhere)