7

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
kag0
  • 5,624
  • 7
  • 34
  • 67

1 Answers1

16

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.

kag0
  • 5,624
  • 7
  • 34
  • 67
  • We had a java program that ran fine for 8 months, and then failed the last week of the year because of the YYYY issue. (The last week being between Christmas and New Years, when half of the devs were on vacation.) I changed the YYYY to yyyy and it gave me the correct year. Thanks kag0 – Phill Z Dec 29 '20 at 00:15
  • This blog post has a good code example of the difference between YYYY and yyyy - http://dangoldin.com/2019/01/06/javas-simpledateformat-yyyy-vs-yyyy/ – Phill Z Dec 29 '20 at 16:23