Java8 appendPattern 与 appendValue 方法定义的模式产生不同的结果

标签 java datetime java-8 java-time

我的代码中有模式“ddMMyy”,我使用 appendValue 方法指定了它:

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                    .appendValue(ChronoField.DAY_OF_MONTH, 2)
                    .appendValue(ChronoField.MONTH_OF_YEAR, 2)
                    .appendValue(ChronoField.YEAR_OF_ERA, 2)
                    .toFormatter();
System.out.println(LocalDate.parse("100199", dateTimeFormatter));

然而,这会为年份生成“0099”:

0099-01-10

如果我将其更改为使用 appendPattern 那样:

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                    .appendPattern("ddMMyy")
                    .toFormatter();
System.out.println(LocalDate.parse("100199", dateTimeFormatter));

我得到了带有世纪的“2099”年的正确结果。

2099-01-10

代码对我来说似乎是等价的,为什么它不产生相同的结果?为什么在第一种情况下缺少世纪?

最佳答案

因为 appendValue 在没有进一步操作的情况下传递了年份 - 在您的例子中是 99。

如果您想从“基准年”开始,比如 2000 年,并将值添加到该基准年(以获得 2099),您可以改用 appendValueReduced:

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
        .appendValue(ChronoField.DAY_OF_MONTH, 2)
        .appendValue(ChronoField.MONTH_OF_YEAR, 2)
        .appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2, LocalDate.of(2000, 1, 1))
        .toFormatter();

当您使用yy 模式时,默认情况下您会获得该行为,详见the javadoc。 :

Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a reduced two digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive. [...]

关于Java8 appendPattern 与 appendValue 方法定义的模式产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38398078/

相关文章:

Java 相当于 .net 回收

php date->diff() 返回无意义的金额

java - 如何将带时区的 PostgreSQL 时间戳转换为 Java Instant 或 OffSetDateTime?

lambda - 可以定义 lambda 表达式的返回类型吗?

java - 在Java程序中创建常量的最佳方式是怎样的?

java.net.绑定(bind)异常 : bind failed: EADDRINUSE

excel - 在 Excel 中将字符串转换为纪元时间

Mac 上的 Docker : No space left on device

java - Java 8 中的默认 ArrayList 大小是多少

Java Swing JTextField setInputVerifier 保持关注 TextField