Java SimpleDateFormat parse Timezone like America/Los_Angeles

牧云@^-^@ 提交于 2019-12-18 06:52:14

问题


I want to parse the following string in Java and convert it to a date:

DTSTART;TZID=America/Los_Angeles:20140423T120000

I tried this:

SimpleDateFormat sdf = new SimpleDateFormat("'DTSTART;TZID='Z':'yyyyMMdd'T'hhmmss");
Date start = sdf.parse("DTSTART;TZID=America/Los_Angeles:20140423T120000");

And this:

SimpleDateFormat sdf = new SimpleDateFormat("'DTSTART;TZID='z':'yyyyMMdd'T'hhmmss");
Date start = sdf.parse("DTSTART;TZID=America/Los_Angeles:20140423T120000");

But it still doesn't work. I think the problem is in America/Los_Angeles. Can you help me please?

Thank you


回答1:


Try this one using TimeZone.

Note: You have to split your date string before doing this operation.

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'hhmmss");

    TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
    sdf.setTimeZone(tz);

    Date start = sdf.parse("20140423T120000");

In SimpleDateFormat pattern Z represent RFC 822 4-digit time zone

For more info have a look at SimpleDateFormat#timezone.




回答2:


If you look for a solution how to parse the whole given string in one and only one step then Java 8 offers this option (the pattern symbol V is not supported in SimpleDateFormat):

// V = timezone-id, HH instead of hh for 24-hour-clock, u for proleptic ISO-year
DateTimeFormatter dtf = 
  DateTimeFormatter.ofPattern("'DTSTART;TZID='VV:uuuuMMdd'T'HHmmss");
ZonedDateTime zdt = 
  ZonedDateTime.parse("DTSTART;TZID=America/Los_Angeles:20140423T120000", dtf);
Instant instant = zdt.toInstant();

// if you really need the old class java.util.Date
Date jdkDate = Date.from(instant);


来源:https://stackoverflow.com/questions/23242211/java-simpledateformat-parse-timezone-like-america-los-angeles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!