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?
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
So YYYY
is using the week-based-year, when we actually wanted yyyy
, the year-of-era.
See this related question or the Wikipedia article on week dates for the difference.
So the pattern we want is MM-d-yyyy
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With