Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

java - 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??

question from:https://stackoverflow.com/questions/66065188/localdatetime-formatter-changing-year-from-2020-to-2021

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...