Search code examples
javalocaldatetime

LocalDateTime formatter changing year from 2020 to 2021?


I am trying to take a date formatted String, parse it to LocalDateTime, then format it back to a String for display. What I found when doing this is that the original string is year 2020 and the LocalDateTime object also has the year 2020. But when I format the LocalDateTime for display, this String somehow is now year 2021? Here's the code:

public class LocalDateTimeTry {
public static void main(String[] args) {
    String originalData = "2020-12-29T20:01:06+0000";
    
    DateTimeFormatter originalFormatter = 
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxxx");
        
    LocalDateTime originalParsed 
        = LocalDateTime.parse(originalData, originalFormatter); 
    
    DateTimeFormatter displayFormatter
        = DateTimeFormatter.ofPattern("MMMM d, YYYY");
    
    String displayFormatted
        = displayFormatter.format(originalParsed);
    
    System.out.printf("Original String of data : %s%n", originalData);
    System.out.printf("LocalDateTime.toString(): %s%n", originalParsed.toString());
    System.out.printf("Formatted for display   : %s%n", displayFormatted);
}
}

The output looks like this: See how the year changes from 2020 to 2021.

Original String of data : 2020-12-29T20:01:06+0000
LocalDateTime.toString(): 2020-12-29T20:01:06
Formatted for display   : December 29, 2021

Any thoughts??


Solution

  • As @Andy Turner pointed out in the comments, the problem comes from this statement:

    DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("MMMM d, YYYY");
    

    where, according to the docs, Y means a week-based-year, y means year-of-era, and u means simply year.

    Therefore, these two variants should produce the correct year for you:

    DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("MMMM d, yyyy");
    DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("MMMM d, uuuu");
    

    Now to understand why y and Y are different and why do they lead to your problem, I found this already discussed here on SO: https://stackoverflow.com/a/62690443/9698467