开发者

Java simple date format british time

开发者 https://www.devze.com 2023-01-01 21:27 出处:网络
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\");

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,West开发者_如何学Goern 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消