java - LocalDate 正在默默地纠正错误的日期?

标签 java date

我预计会有异常(exception):

LocalDate.parse("9/31/2018",DateTimeFormatter.ofPattern("M/d/yyyy"));

但是我得到的是 2018 年 9 月 30 日!?不要误会我的意思,它很聪明,这很好,但我开始期望 Java 的 Date 类具有更高的精度......

谁能解释一下如何/为什么?这会扰乱我的测试。

最佳答案

这是由于 ResolverStyle格式化程序使用它来解析该值。默认情况下(至少在我的机器上)它是“智能的”:

For example, resolving year-month and day-of-month in the ISO calendar system using smart mode will ensure that the day-of-month is from 1 to 31, converting any value beyond the last valid day-of-month to be the last valid day-of-month.

...但您可以将其设置为“严格”,在这种情况下解析会失败。完整示例(使用 u 而不是 y 以避免未指定时代的歧义):

import java.time.*;
import java.time.format.*;

public class Test {

    public static void main (String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/uuuu");
        // With the "smart" resolver style, it parses
        System.out.println(formatter.getResolverStyle());
        LocalDate date = LocalDate.parse("9/31/2018", formatter);
        System.out.println(date);

        // But with a strict style...
        formatter = formatter.withResolverStyle(ResolverStyle.STRICT);
        LocalDate.parse("9/31/2018", formatter);
    }
}

关于java - LocalDate 正在默默地纠正错误的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56029619/

相关文章:

linux - 替换 JSON 配置文件中的日期

显示所有(轻量级)标签创建日期的 git 命令

java - 如何在java中创建图形对象?

java - 在 Java 中创建具有偏移量的 Date 对象

java - 使用 volley 进行网络操作时如何显示 ProgressDialog

java - JPA 事件监听器不工作

javascript - Firefox 上的 moment.js 问题

java - 如何在android中从 "Monday"获取像 "2015-02-24"字符串这样的一天

java - 使用 lambda 迭代集合时使用 setter 方法

java - Servlet 启动外部进程