Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SimpleDateFormat parse Timezone like America/Los_Angeles

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

like image 217
Lorenzo Tassone Avatar asked Dec 04 '22 06:12

Lorenzo Tassone


2 Answers

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.

like image 138
Braj Avatar answered Jan 12 '23 15:01

Braj


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);
like image 32
Meno Hochschild Avatar answered Jan 12 '23 14:01

Meno Hochschild