Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does formatting a date using DateTimeFormatter with a YYYY pattern give the wrong year? [duplicate]

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?

like image 571
kag0 Avatar asked Jul 02 '18 18:07

kag0


1 Answers

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.

like image 178
kag0 Avatar answered Oct 29 '22 18:10

kag0