Skip to content
Advertisement

Java – ZonedDateTime does not correctly convert to Date object?

I have the following Java code:

JavaScript

The Issue I am having is that convertedDateis not correct in comparison to the zonedDateTime object.

For Example when I have a zonedDateTime object of:

JavaScript

with zone:

JavaScript

The code above converts this to:

JavaScript

What I would be expecting here is

JavaScript

As the Africa/Abidjan timezone is 2 hours ahead of BST.

How can I solve this?

Advertisement

Answer

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

JavaScript

Output:

JavaScript

ONLINE DEMO

  • The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

  • From the output, it is clear that 2021-09-16T12:00Z[Africa/Abidjan] is equal to 2021-09-16T13:00+01:00[Europe/London].

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Advertisement