【问题标题】:DateTimeFormatter exceptionDateTimeFormatter 异常
【发布时间】:2016-09-23 07:27:59
【问题描述】:

我在使用 Java 中的 DateTimeFormatter 时遇到问题。

我有以下代码:

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDateTime startDate = LocalDateTime.now();
LocalDateTime endDate = LocalDateTime.parse(ceremonyDetails.getDate(), format);
System.out.println(ChronoUnit.DAYS.between(startDate, endDate)); format);

应该从字符串中打印从现在到日期之间的天数,格式为“dd/MM/yyyy”,例如“29/09/2016”。

但是,我收到此错误:

java.time.format.DateTimeParseException: 文本 '29/09/2016' 不能 被解析:无法从 TemporalAccessor 获取 LocalDateTime: {},ISO 解析为 java.time.format.Parsed 类型的 2016-09-29] 根本原因 java.time.DateTimeException:无法获取 LocalTime 从 TemporalAccessor: {},ISO 解析为 2016-09-29 类型 java.time.format.Parsed

我错过了什么?

【问题讨论】:

  • 我不知道你是如何添加这个日期的,是在代码中,也许你应该转义 / ?
  • @BertVerhees,在我的调试器中,日期正好是 '29/09/2016'
  • @ScaryWombat,我刚刚明白了。这就是问题所在:)

标签: java


【解决方案1】:

您应该使用LocalDate 而不是LocalDateTime。一个用于仅日期值,另一个用于具有时间值的日期。

LocalDate.parse( "29/09/2016" , DateTimeFormatter.ofPattern("dd/MM/yyyy") )

查看DateTimeFormatter 类文档页面上的示例。

【讨论】:

    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2020-08-11
    相关资源
    最近更新 更多