LocalDate DateTimeFormatter问题

问题描述 投票:2回答:1

我已经阅读了手册,完全不知道为什么此代码不起作用。

    // Date Entered must be valid
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy")
            .withResolverStyle(ResolverStyle.STRICT);

    try {
        String dateEntered = lossDateMonth + "/" + lossDateDay + "/" + lossDateYear; // Slash to match UI

        System.out.println(dateEntered);
        LocalDate dateParsed = LocalDate.parse(dateEntered, dateTimeFormatter);

println语句打印:2015年7月29日

最后一行抛出异常:java.time.format.DateTimeParseException:无法解析文本“ 07/29/2015”:无法从TemporalAccessor获取LocalDate:{YearOfEra = 2015,DayOfMonth = 29,MonthOfYear = 7},类型为java.time.format的ISO 。解析

我阅读了此手册,它说如果您尝试解决一个不存在的日期(例如9月31日),则会发生这种情况。即使出现错误,解析器似乎也知道我在问2015年7月29日左右,所以我在这里做错了什么?

java localdate
1个回答
3
投票

"MM/dd/yyyy"替换样式"MM/dd/uuuu"。看一下DateTimeFormatterIsoChronology。问题在于,当使用.withResolverStyle(ResolverStyle.STRICT)时,格式化程序期望由uuuu提供的年份的唯一标识符,其中yyyy时代。这是严格验证值。通过uuuu可以为负的事实来给出唯一性。

查看相关文章的hereherehere

© www.soinside.com 2019 - 2024. All rights reserved.