How to parse a UTC offset dateformat string into the resulting date separated by | symbol

Angela Heely :

I have a very peculiar question where I am trying to parse "2019-12-25T17:00:00-05:00" such that it should give me the result DEC 12 | Thursday | 5:00pm

I tried the following code by using DateTimeFormatter and LocalDate

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz", Locale.US);
                DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM d | E | hh:mm a", Locale.US);
                LocalDate date = LocalDate.parse("2019-12-25T17:00:00-05:00", inputFormatter);
                String formattedDate = outputFormatter.format(date);
                contentTextView.setText(formattedDate);

but it crashes with DateTimeParseException: Text '2019-12-25T17:00:00-05:00' could not be parsed at index 19

Any idea why it's crashing and if my output will render the expected result? Thanks!

Deadpool :

Your String 2019-12-25T17:00:00-05:00 represents UTC timezone with offset UTC offset, so use OffsetDateTime for parsing that string

OffsetDateTime odt = OffsetDateTime.parse("2019-12-25T17:00:00-05:00");

System.out.println(odt.format(DateTimeFormatter.ofPattern("MMM d | E | hh:mm a", Locale.US)));

If you want to set particular time zone you can use atZoneSameInstant to pass ZoneId for eaxmple

ZoneId zone = ZoneId.of("America/Chicago");
ZonedDateTime zdt = odt.atZoneSameInstant(zone);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125729&siteId=1