I have a Java class that takes in the latitude/longitude of a location and returns the GMT offset when daylight savings time is on and off. I am looking for an easy way to determine in Java if the current date is in daylight savings time so I can apply the correct offset. Currently I am only performing this calculation for U.S. timezones although eventually I would like to expand this to global timezones as well.
views:
1791answers:
4This is the answer for the machine on which the question is being asked:
TimeZone.getDefault().isDaylightTime( new Date() );
A server trying to figure this out for a client will need the client's time zone. See @R. Bemrose answer for the reason why.
For any particular TimeZone
TimeZone.getTimeZone( "US/Alaska").isDaylightTime( new Date() );
TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());
You're going to have to do a bit more work using those coordinates and figure out which time zone they're in. Once you know which TimeZone that is, the isDayLight() method would be useful.
For example, you have no way of telling whether -0500 is EST (US/Canada Eastern Standard Time), CDT (US/Canada Central Daylight Time), COT (Columbia Time), AST (Brazil Acre Standard Time), ECT (Ecuador Time), etc...
Some of these may or may not support daylight saving time.
Joda Time contains handling methods which will calculate the offsets for you. See DateTimeZone.convertLocalToUTC(...)
To supplement this, you will need to look up the current time zone with your latitude/longitude info. GeoNames provides a java client for its web service, as well as a simple web-request framework (i.e. http://ws.geonames.org/timezone?lat=47.01&lng=10.2)