Skip to content
Advertisement

Convert java.time.Instant to java.sql.Timestamp without Zone offset

In the application I am developing, I need to convert java.time.Instant object to java.sql.Timestamp. When I create Instant object like:

JavaScript

I receive something like 2017-03-13T14:28:59.970Z. And when I try to create Timestamp object like this:

JavaScript

I receive something like 2017-03-13T16:28:59.970Z. The same result but with an additional 2 hour delay. Can someone explain why this is happening and provide me with an answer to fix this problem without this delay?

When I created like this:

JavaScript

Everything works well, but I try to avoid conversions. Is there a way to do this by only using Instant object?

Advertisement

Answer

I changed my computer’s time zone to Europe/Bucharest for an experiment. This is UTC + 2 hours like your time zone.

Now when I copy your code I get a result similar to yours:

JavaScript

Output is given in comments. However, I go on:

JavaScript

Now you can see that the Timestamp really agrees with the Instant we started out from (only the milliseconds are not printed, but I trust they are in there too). So you have done everything correctly and only got confused because when we printed the Timestamp we were implicitly calling its toString method, and this method in turn grabs the computer’s time zone setting and displays the time in this zone. Only because of this, the displays are different.

The other thing you attempted, using LocalDateTime, appears to work, but it really does not give you what you want:

JavaScript

Now when we print the Timestamp using our UTC DateFormat, we can see that it is 2 hours too early, 04:16:32 UTC when the Instant is 06:16:32 UTC. So this method is deceiving, it looks like it’s working, but it doesn’t.

This shows the trouble that lead to the design of the Java 8 date and time classes to replace the old ones. So the real and good solution to your problem would probably be to get yourself a JDBC 4.2 driver that can accept an Instant object readily so you can avoid converting to Timestamp altogether. I don’t know if that’s available for you just yet, but I’m convinced it will be.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement