Java SimpleDateFormat解析Timezone,如America / Los_Angeles
我想在Java中解析以下字符串并将其转换为日期:
DTSTART;TZID=America/Los_Angeles:20140423T120000
我试过这个:
SimpleDateFormat sdf = new SimpleDateFormat("'DTSTART;TZID='Z':'yyyyMMdd'T'hhmmss"); Date start = sdf.parse("DTSTART;TZID=America/Los_Angeles:20140423T120000");
和这个:
SimpleDateFormat sdf = new SimpleDateFormat("'DTSTART;TZID='z':'yyyyMMdd'T'hhmmss"); Date start = sdf.parse("DTSTART;TZID=America/Los_Angeles:20140423T120000");
但它仍然无效。 我认为问题出在America / Los_Angeles。 你能帮我吗?
谢谢
使用TimeZone尝试这个。
注意:在执行此操作之前,您必须拆分日期字符串。
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'hhmmss"); TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); sdf.setTimeZone(tz); Date start = sdf.parse("20140423T120000");
在SimpleDateFormat
模式中, Z
表示RFC 822 4-digit time zone
有关更多信息,请查看SimpleDateFormat #timezone 。
如果您寻找一个解决方案如何在一个步骤中解析整个给定字符串,那么Java 8提供此选项( SimpleDateFormat
不支持模式符号V ):
// 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);