views:

1791

answers:

4

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.

+2  A: 

This 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() );
Clint
I have been working on this same problem. I have not found a shape file for the world time zones.
Clint
We don't know if this is a desktop app or a web app, though. A Web app wouldn't have access to the time zone information on the client.
R. Bemrose
+1  A: 
TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());
mamboking
I hate to think of what happens when TimeZone.inDaylightTime() returns false, and suddenly yes == no
Jeremy Frey
Careful, or someone will start a "what's the worst variable name" question, and only suffering will come from that.
skaffman
Point taken. Edited.
mamboking
+1  A: 

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.

R. Bemrose
A: 

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)

James Van Huis
I've looked into the GeoNames web service previously and I am aware it will accomplish what I am trying to do. Unfortunately this code will be hosted on servers that may be located behind a firewall so I'm trying to avoid external web service calls if possible. For those without this restriction the GeoNames web service would be a great solution.
gelgamil