【问题标题】:Using ZoneDateTime.parse how would you parse the following使用 ZoneDateTime.parse 你将如何解析以下内容
【发布时间】:2019-07-22 16:39:47
【问题描述】:

使用 ZoneDateTime.parse,你将如何解析以下内容

2019 年 7 月 1 日星期一 00:00:00 GMT-0500(中部夏令时间)

必须使用 zoneDateTime.parse 是必须的。

这不是为了家庭作业,而是为了工作和标准已经设定。

【问题讨论】:

  • 你搜索过吗?你发现了什么?哪方面不够?你试过什么吗?它以什么方式失败了?
  • 你见过ZonedDateTimedocumentation吗?

标签: java date datetime parsing


【解决方案1】:

要解决这样的问题,首先尝试构建一个可以产生相同输出的格式化程序。然后用它来解析。

阅读 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]

【讨论】:

  • 很好的答案,解释得很好。我建议为格式化程序指定一个说英语的语言环境。
猜你喜欢
  • 1970-01-01
  • 2013-05-31
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多