java.time
…and what can I do?
- Decide on a time zone.
- Use java.time, the modern Java date and time API.
For example:
ZoneId zone = ZoneId.of("America/Glace_Bay");
ZonedDateTime dateTime = ZonedDateTime.of(2019, 10, 27, 12, 34, 56, 0, zone);
System.out.println(dateTime);
Output is:
2019-10-27T12:34:56-03:00[America/Glace_Bay]
Don’t use Date
. That class was always poorly designed. There is a reason why most constructors and most methods were deprecated very quickly. They don’t work reliably across time zones. Today we have so much better in java.time.
Only if you need a Date
for a legacy API that you cannot afford to upgrade to java.time just now, convert like this:
Instant pointInTime = dateTime.toInstant();
Date oldFashionedDate = Date.from(pointInTime);
System.out.println(oldFashionedDate);
Output in my time zone is:
Sun Oct 27 15:34:56 GMT 2019
The time of day doesn’t agree with what we specified. This is because I am in a different time zone. Date.toString
(called from System.out.println
) renders the date in the default time zone of the JVM, which has confused many over the years (it’s just one of the many reasons to avoid that class). The Date
does represent the correct point in time, and you can use it for your legacy API.
What does it mean for a constructor to be deprecated,…
Many have explained that nicely already. I haven’t taken the deprecation from the 1990s as a promise to remove the constructor. In Java 9 they introduced the possibility of marking a deprecated item for removal. I am still curious to see whether they will mark this constructor for removal at some point.
Links