为了账号安全,请及时绑定邮箱和手机立即绑定

java.time.format.DateTimeParseException:

java.time.format.DateTimeParseException:

跃然一笑 2022-09-07 16:56:55
我在将字符串格式化为ZonedDateTime时遇到问题。我的客户希望日期采用 ddMMyyhhmmss 等格式,没有分隔符或类似的东西。这是我到目前为止所做的import java.time.format.DateTimeFormatter;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;public class MyClass {    public static void main(String args[]) {            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyhhmmss");            String test = formatter            .format(ZonedDateTime.now()).toString();            System.out.println(test);            ZonedDateTime a = ZonedDateTime.parse(test,formatter);            System.out.println(a.toString());    }}当它正确生成字符串时,错误发生在创建 LocalDateTime 变量的解析过程中28032019100707Exception in thread "main" java.time.format.DateTimeParseException: Text '28032019100707' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=7, HourOfAmPm=10, NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=7},ISO resolved to 2019-03-28 of type java.time.format.Parsed    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)    at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)    at MyClass.main(MyClass.java:14)在SO上搜索,我看到同一问题的一些答案建议使用LocalDateTime类作为中间类,然后解析为ZonedDateTime,但它仍然不起作用,抛出了相同的错误。我还尝试使用此过程更改初始化DateTimeFormatter的方式DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("ddMMyyyyhhmmss")                          .toFormatter()                          .withZone(ZoneId.systemDefault());但它仍然不起作用。我知道我肯定错过了一些愚蠢的东西,但我看不到什么。任何人都可以给我指出正确的方向吗?
查看完整描述

3 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

你想要:

  String test = ZonedDateTime.now().format(formatter);


查看完整回答
反对 回复 2022-09-07
?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

ddMMyyyyhhmmss不包含任何区域信息,它不是,它应该是 。ZonedDateTimeLocalDateTime



查看完整回答
反对 回复 2022-09-07
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

在您解析的字符串中,没有关于时区的信息 - 那么格式化程序应该如何知道如何转换为ZonedDateTime?

您需要在字符串中包含时区信息,或者使用另一个对象将其解析为没有时区信息,然后将其传输到所需的区域中。


查看完整回答
反对 回复 2022-09-07
  • 3 回答
  • 0 关注
  • 517 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号