将DateTimeFormatter
(具有以下模式)与LocalDate
一起使用会导致错误的年份。
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)
为什么会这样?
答案 0 :(得分:1)
之所以会这样,是因为模式MM-d-YYYY
并不是我们认为的那样。
如果我们看the documentation,就会看到
Symbol Meaning Presentation Examples
------ ------- ------------ -------
y year-of-era year 2004; 04
Y week-based-year year 1996; 96
因此YYYY
使用的是基于周的年份,而我们实际上希望使用yyyy
,即年份。
有关差异,请参见this related question或the Wikipedia article on week dates。
所以我们想要的模式是MM-d-yyyy
。