Parse date with "America/New_York" like time zones

Viewed 56

Trying to parse a date with a detailed time zone:

var sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sdf.parse("2022-09-02 02:30:10 America/New_York");

Getting:

java.text.ParseException: Unparseable date: "2022-09-02 02:30:10 America/New_York"

Tried: specifying "z", "zzz", "X" and "XXX" in the date formatter.

1 Answers

You can use the modern Time API with a DateTimeFormatter instead. The symbol for a (long) Zone-id is VV.

For example

System.out.println(ZonedDateTime.parse(
                         "2022-09-02 02:30:10 America/New_York", 
                         DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss VV")));

Outputs

2022-09-02T02:30:10-04:00[America/New_York]
Related