I have a collection of Java Date objects, loaded from an old database which did not store timezone info.
I know that all the dates (which include hours, minutes and seconds) are for the U.S. Eastern time zone.
I want to derive the correct timezone abbreviation ("EST" or "EDT") for each date.
Here is my attempt (using Java 11). It is unwieldy, to say the least.
I looked into the following classes:
java.util.TimeZone
java.time.ZoneId
java.time.zone.ZoneRules
Here is my method - it uses two statements purely to give me a fighting chance of still understanding what I wrote, a week from now.
EDIT - based on @VGR's comment below, I have updated the example. Now it expects a timezone display name - for example "America/New_York"
:
public String getTimezoneAbbrev(Date date, String tzName) {
TimeZone tz = TimeZone.getTimeZone(tzName);
boolean isDaylightSavings = tz.toZoneId().getRules().isDaylightSavings(date.toInstant());
return tz.getDisplayName(isDaylightSavings, TimeZone.SHORT);
}
It works (I have test cases), but is there a less verbose way?
(I did not find any code examples which use Date
as their starting point).