简体   繁体   中英

Java simple date format british time

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: eg

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

However, if someone is always sending time in London time (ie taking into account daylight savings), what would be the approriate time zone String to add? eg 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.

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

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM