【问题标题】:Java 8 LocalDate won't parse valid date string [duplicate]Java 8 LocalDate 不会解析有效的日期字符串 [重复]
【发布时间】:2019-02-25 02:35:51
【问题描述】:

这里是 Java 8。我有以下代码:

final String createdDateStr = "20110920";
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMMdd");
final LocalDate localDate = LocalDate.parse(createdDateStr, formatter);

在运行时我得到以下异常:

java.time.format.DateTimeParseException: Text '20110920' could not be parsed at index 0

    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.

...被LocalDate.parse(...) 调用抛出。 解析器出了什么问题?!

【问题讨论】:

  • 没错。整个错误消息是Exception in thread "main" java.time.format.DateTimeParseException: Text '20110920' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=9, WeekBasedYear[WeekFields[SUNDAY,1]]=2011, DayOfMonth=20},ISO of type java.time.format.Parsed“WeekBasedYear”提示您格式不正确。 OP想要“y”但写了“Y”。可能是一个常见的错误。 :)
  • Parsing a string to date format in java defaults date to 1 and month to January 中的问题相同,但症状不同。是的,一个常见的错误,@RayToal。

标签: java datetime java-8 datetime-format localdate


【解决方案1】:

来自the documentation的例子:

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);

您应该使用"yyyyMMdd" 而不是"YYYYMMdd"Yy 之间的区别提到了 here

【讨论】:

    【解决方案2】:

    无需手动指定格式。它已经内置了。

        final String createdDateStr = "20110920";
        final DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
        final LocalDate localDate = LocalDate.parse(createdDateStr, formatter);
        System.out.println(localDate);
    

    这个输出:

    2011-09-20

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 2019-10-27
      • 2019-08-26
      • 2021-08-10
      • 1970-01-01
      • 2013-01-21
      相关资源
      最近更新 更多