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 - 使用 java 流将 String[] str = {"a","b","c","d","e","f"} 映射为 {a=b, c=d, e=f}

validation - Jersey 2.6 REST 服务升级到 Java 8 tomcat 8 异常 :java. lang.NoSuchMethodError : javax. validation.Configuration.getBootstrapConfiguration

java - Java 中形成匹配谓词集合的对象集合的最快方法是什么?

java - 无法解析接口(interface) 26 Landroid/content/ClipboardManager$OnPrimaryClipChangedListener;'

java - log4j xml配置,将一些Logger写入文件和控制台

python - 使用 .dst() 函数测试 datetime.datetime 是否处于夏令时,不返回带有 pytz 时区的值

php - 如何列出 DATETIME 数据的年龄明智结果

java - 如何使用JSP动态编辑表?

java - 下载maven中的存储库

ios - 设置当前时间为yyyy-MM-dd 00 :00:00 using Swift