为什么使用带有 YYYY 模式的 DateTimeFormatter 格式化日期会给出错误的年份? [英] Why does formatting a date using DateTimeFormatter with a YYYY pattern give the wrong year?

查看:66
本文介绍了为什么使用带有 YYYY 模式的 DateTimeFormatter 格式化日期会给出错误的年份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 DateTimeFormatter(使用下面的模式)和 LocalDate 会导致错误的年份.

Using DateTimeFormatter (with the pattern below) with a LocalDate results in the wrong year.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

DateTimeFormatter format = DateTimeFormatter.ofPattern("MM-d-YYYY");
LocalDate date = LocalDate.of(2018, 12, 31);

date.format(format); // returns 12-31-2019 (expected 2018)

为什么会发生这种情况?

Why does this happen?

推荐答案

发生这种情况是因为模式 MM-d-YYYY 不是我们认为的那样.

This happens because the pattern MM-d-YYYY isn't what we think it is.

如果我们查看文档 我们看到

If we look at the documentation we see

 Symbol  Meaning                     Presentation      Examples  
 ------  -------                     ------------      -------  
 y       year-of-era                 year              2004; 04  
 Y       week-based-year             year              1996; 96

所以 YYYY 使用的是基于周的年份,而我们实际上想要 yyyy,即时代的年份.

So YYYY is using the week-based-year, when we actually wanted yyyy, the year-of-era.

参见这个相关问题有关周日期的维基百科文章 以了解差异.

所以我们想要的模式是MM-d-yyyy.

So the pattern we want is MM-d-yyyy.

这篇关于为什么使用带有 YYYY 模式的 DateTimeFormatter 格式化日期会给出错误的年份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆