tags:

views:

86

answers:

3

Hi, I am using simple date format to allow users to specify which time zone they are sending data in:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,z");

This works fine: e.g.

df.parse("2009-05-16 11:07:41,GMT");

However, if someone is always sending time in London time (i.e. taking into account daylight savings), what would be the approriate time zone String to add? e.g. this doesnt work:

df.parse("2009-05-16 11:07:41,Western European Time");  
System.out.println(date);
Sat May 16 12:07:41 BST 2009

I want to match the time to british time taking into daylight savings.

Thanks.

A: 

So what exactly is your question - what ID for the TimeZone you should use? The following will print a list of all the available time zone identifiers:

for (String id : TimeZone.getAvailableIDs()) {
    System.out.println(id);
}
Jesper
doesnt help....the id is irrelevant for parsing.
DD
+2  A: 

In daylight saving time, it's BST. In the rest of the year it's GMT.

I suggest that you use the generic name (for the whole year), which is Europe/London. You can use something like this:

    String userInput = "2009-05-16 11:07:41,Europe/London";
    String[] tokens = userInput.split(",");

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone(tokens[1]));
    System.out.println(df.parse(tokens[0]));

The output in this case is:

Sat May 16 11:07:41 GMT+01:00 2009
Bruno Rothgiesser
defeats the whole point of letting the user specify the timezone in the parse string
DD
@DD - no, it doesn't. You can still let the user specify a date like 2009-05-16 11:07:41,Europe/London and split that string in the code by comma.
Bruno Rothgiesser
I've just edited my answer to illustrate that.
Bruno Rothgiesser
A: 

I don't think it's possible to do exactly what you want to do using SimpleDateFormat on its own. TimeZone.parse(String) only accepts time zones, not time zone IDs, for example:

Time Zone ID       Time Zone (Winter)      Time Zone (Summer)
-------------------------------------------------------------
Europe/London      GMT                     BST

If parse(...) accepted Europe/London there would be one hour in spring that would not be a valid Europe/London time and one hour in autumn that would map to two UTC times.

I think that the best you can do is follow Bruno Rothgiesser's suggestion, however you could accept the time zone ID as a separate user input, or do an additional string processing step to separate the time zone id from the user input string, and use it to work out whether the user probably means GMT or BST. The user's Locale might be a better way of working out what he/she means - although there are some assumptions involved in that idea.

The "what the user probably means" algorithm has to deal with two special cases - you can use TimeZone.inDaylightTime(Date) with userTime +/- 1 hour to work out if you might have one of these.

richj