要解决这样的问题,首先尝试构建一个可以产生相同输出的格式化程序。然后用它来解析。
阅读 DateTimeFormatter 的 javadoc,了解哪些格式符号可以产生所需的输出。
Mon E day-of-week text Tue; Tuesday; T
Jul M/L month-of-year number/text 7; 07; Jul; July; J
01 d day-of-month number 10
2019 u year year 2004; 04
00 H hour-of-day (0-23) number 0
: : fixed text
00 m minute-of-hour number 30
: : fixed text
00 s second-of-minute number 55
GMT 'GMT' fixed text
-0500 x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
( ( fixed text
Central Daylight Time z time-zone name zone-name Pacific Standard Time; PST
) ) fixed text
然后阅读细则以了解您需要的每种格式字母的数量,例如您需要 dd 才能获得前导零的 2 位数月份日期。
测试结果:
String expected = "Mon Jul 01 2019 00:00:00 GMT-0500 (Central Daylight Time)";
String format = "EEE MMM dd uuuu HH:mm:ss 'GMT'xx (zzzz)";
ZonedDateTime zdt = ZonedDateTime.of(2019, 7, 1, 0, 0, 0, 0, ZoneId.of("America/Chicago"));
System.out.println(zdt.format(DateTimeFormatter.ofPattern(format)));
System.out.println(expected);
输出
Mon Jul 01 2019 00:00:00 GMT-0500 (Central Daylight Time)
Mon Jul 01 2019 00:00:00 GMT-0500 (Central Daylight Time)
使用它
String input = "Mon Jul 01 2019 00:00:00 GMT-0500 (Central Daylight Time)";
String format = "EEE MMM dd uuuu HH:mm:ss 'GMT'xx (zzzz)";
ZonedDateTime zdt = ZonedDateTime.parse(input, DateTimeFormatter.ofPattern(format));
System.out.println(zdt);
输出
2019-07-01T00:00-05:00[America/Chicago]