【问题标题】:DateTimeFormatter throwing exception "could not be parsed at index 0" [duplicate]DateTimeFormatter 抛出异常“无法在索引 0 处解析”[重复]
【发布时间】:2020-11-12 01:15:27
【问题描述】:

我不断收到运行此代码的错误。

java.time.format.DateTimeParseException:无法在索引 0 处解析文本“2020 年 1 月 3 日”

final String myFormat = "LLL dd, yyyy"; //sets format in which to show date (same as how its saved in database) ex. Jan 29, 2020
final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(myFormat);

String startingBiWeeklyCheck = sharedPreferences.getString("biweekly start", "Jan 03, 2020");
            LocalDate startingDate = LocalDate.parse(startingBiWeeklyCheck, dateFormatter);

我使用过这种格式,但我不明白为什么模式“LLL dd, yyyy”无法解析 2020 年 1 月 3 日

【问题讨论】:

    标签: java android java-time


    【解决方案1】:

    您应该使用MMM 而不是LLL 进行月份解析。

    更新:

    我上面的回答错了。这是答案的一半。

    交易是DateTimeFormatter.ofPattern(myFormat),使用默认Locale。 对于非美国语言环境,它不起作用。 所以你需要根据你的模式指定语言环境。

    DateTimeFormatter.ofPattern(myFormat).withLocale(Locale.US)
    

    【讨论】:

    • 将格式更改为“MMM dd, yyyy”会引发同样的异常。
    • 检查您的 startingBiWeeklyCheck 变量输出。它应该始终返回一个与您在myFormat 中指定的模式相同的字符串
    • 顺便问一下,你的语言环境是什么?也尝试设置DateTimeFormatter.ofPattern(myFormat).withLocale(Locale.US)
    • @Ole V.V.这实际上很有趣,因为看看doc M/L month-of-year number/text 7; 07; Jul; July; J。所以L代表数字,M代表文本值。在我的AdoptOpenJDK 1.8.0_262-b10 上,反之亦然!
    • 这是我的输出pastebin.com/MnrFwJrb
    猜你喜欢
    • 1970-01-01
    • 2020-08-15
    • 2020-02-01
    • 2020-06-25
    • 1970-01-01
    • 2011-12-26
    • 2018-04-04
    • 2020-06-10
    • 2018-12-12
    相关资源
    最近更新 更多