I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

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);
assertEquals(instant.toEpochMilli(), timestamp.getTime());

And vice-versa, we can use Timestamp.toInstant() to convert Timestamps into Instants:

instant = timestamp.toInstant();
assertEquals(instant.toEpochMilli(), timestamp.getTime());

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 timezone 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:

DateFormat df = DateFormat.getDateTimeInstance();
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SS'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));

assertEquals(instant.toString(), df.format(timestamp).toString());

4. Conclusion

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.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

avatar
  Subscribe  
Notify of