【问题标题】:Format ZonedDateTime [duplicate]格式 ZonedDateTime [重复]
【发布时间】:2019-05-07 11:37:00
【问题描述】:

我需要格式化 ZonedDate 时间以格式化 MM/dd/yyyy

ZonedDateTime zonedDateTime = ZonedDateTime.now();
String date = DateTimeFormatter.ofPattern("MM/dd/yyyy").format(zonedDateTime);
ZonedDateTime zoneDate = ZonedDateTime.parse(date);

得到错误:

线程“main”java.time.format.DateTimeParseException 中的异常:无法在索引 0 处解析文本“12/05/2018”

或者,如果我将我的值转换为我想要的格式的字符串,然后尝试再次使用我的格式将其解析回 ZonedDate Time:

DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
ZonedDateTime zonedDateTime = ZonedDateTime.now();
String date = DateTimeFormatter.ofPattern("MM/dd/yyyy").format(zonedDateTime);
ZonedDateTime zonedate = ZonedDateTime.parse(date, format);

我得到错误:

线程“主”java.time.format.DateTimeParseException 中的异常:无法解析文本“12/05/2018”:无法从 TemporalAccessor 获取 ZonedDateTime:{},ISO 解析为 2018-12-05 类型java.time.format.Parsed

我已经看到很多关于此的问题,但我不断收到这些解析错误

【问题讨论】:

  • 这不是parse 期望的格式。使用 takes a DateTimeFormatter 使用您的格式“MM/dd/yyyy”创建的另一个覆盖它应该解析。
  • 如果您只有月、日和年,您应该使用LocalDate,而不是 ZonedDateTime。
  • @DavidConrad 我编辑了问题,包括我已经尝试过的问题以及收到的错误。
  • 是的,对不起,我看到你的编辑就像我发表的评论一样。
  • @DavidConrad 出于某种原因它仍然无法解析,即使字符串已经按照我想要的方式进行了格式化,并且我将相同的格式传递给 parse 方法。

标签: java datetime-parsing zoneddatetime


【解决方案1】:

有两个问题。首先,日期中没有区域信息,其次,没有时间信息。您可以将其转换为LocalDate

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
ZonedDateTime zonedDateTime = ZonedDateTime.now();
String date = formatter.format(zonedDateTime);
LocalDate localdate = LocalDate.parse(date, formatter);

您可以将LocalDate 转换为ZonedDateTime,方法是将时间设置为一天的开始时间,并将区域设置为默认系统区域。否则,您需要提供时间和您选择的 ZoneId

ZonedDateTime zdt = localdate.atStartOfDay(ZoneId.systemDefault());

【讨论】:

  • 我基本上在这里发现了这个错误 stackoverflow.com/questions/23596530/… 。但是zdt 仍然是默认的 ZonedDateTime 格式。 localdate其实是我想要的格式,但还是需要一个 ZonedDateTime 对象。
  • 此时使用LocalDate 可能是最简单的,就像@VGR 建议的那样
  • 我不明白。 ZonedDateTime 没有任何格式。这就是为什么你必须使用DateTimeFormatter 来格式化它。
  • 也许您的意思是,当您通过调用toString() 将其转换为字符串时,它会以ISO 格式输出。但这并不意味着它是那种格式。它通过调用toString() 转换为该格式,或通过DateTimeFormatter 转换为您想要的任何其他格式。
  • 更正:ZonedDateTime.toString() 没有定义有效的 ISO 格式,因为尾随区域 id 取自 IANA-TZDB,而不是 ISO(只知道偏移量)。
猜你喜欢
  • 2019-05-03
  • 1970-01-01
  • 2019-08-19
  • 2020-12-15
  • 2021-09-04
  • 1970-01-01
  • 2017-05-31
  • 2020-09-20
  • 1970-01-01
相关资源
最近更新 更多