Java SimpleDateFormat parse Timezone like America/Los_Angeles

后端 未结 2 510
[愿得一人]
[愿得一人] 2020-12-19 15:07

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

DTSTART;TZID=America/Los_Angeles:20140423T120000

I tried this:

相关标签:
2条回答
  • 2020-12-19 15:40

    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);
    
    0 讨论(0)
  • 2020-12-19 16:00

    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.

    0 讨论(0)
提交回复
热议问题