Java: Which date/time class to use?
Image by Michal Jarmoluk↗ from Pixabay↗
Java has many classes for dates. There are the ancient implementations of java.util.Date and java.util.Calendar. Since Java 8 there is the new DateTime library with many Classes.
But which one should I use? In which Context?
Here are my favorites:
java.time.LocalDate↗
Use that class if your object is something where the time does not matter.
Real world example:
Birthday. Imagine if you had been born in Europe and moved to Australia you would not start celebrating your birthday in the evening because of the location of your birth.
It’s just the date, no time!
java.time.Instant↗
Use that class if your object is like a technical timestamp. This event occured on the 6th October 2009 at 11:45:34 UTC.
Instant has no timezone information, so please treat all Instants as UTC timestamps!
java.time.ZonedDateTime↗
When shall we three meet again? Next week, same time!
Easy! Just add 7*24*60*60*1000
milliseconds.
Not really! What if there was a switch from daylight saving time on the next sunday?
Use a +01:00
after the timestamp to indicate the timezone.
There are severaltimezones with +01:00
offset, some with daylight saving time and some without, so…
Use ZonedDateTime↗ for anything which is like appointment in real life.
When serializing a ZonedDateTime to a ISO-8601↗ string representation, do not forget to add a textual timezone information. The offset is not enough when dealing with recurring events and daylight saving time!
One more thing…
For unit tests, you might want to simulate something like now we pretend the time is running 5 hours into the future.
You will have some pain to test that using normal methods.
Therefor:
Use a java.time.Clock↗ object in your implementation code to construct date/time objects. In the test code, you can then manipulate the clock to simulate the time standing still or running forward.
Last advice
Try to avoid using java.util.Date↗ and java.util.Calendar↗ by any means possible.
Any comments or suggestions? Leave an issue or a pull request!