kotlin OffsetDateTime format of pattern

I am try to convert a offsetdatetime to a specific format, but i have a problem

OffsetDateTime.parse("2021-12-27T15:49:08Z")
            .format(DateTimeFormatter.ofPattern("EEE dd MMM YYYY, h:mm:ss"))

and it print one year more

lun. 27 dic. 2022, 3:49:08

what is the reason?

thanks a lot


This is because you're specifying the pattern YYYY for the year.

According to the docs for java.time.format.DateTimeFormatter, a pattern of one or more Ys means ‘week-based year’.

That's different from the usual ‘year-of-era’, which you get from a pattern of one or more lower-case ys.

The difference is explained in this question. Basically, if the year starts in the middle of a week, it treats that entire week as falling either in the previous year or the following year.

The exact calculation will depend indirectly upon the locale, as that controls which day the week starts on. (I don't fully understand all the details, but I think it's mediated by the WeekFields class. However it works, it can cause the last few days of 2021 to be treated as part of 2022, as this question demonstrates.)

In any case, it looks like your real problem is using a week-based year number when you just want the normal calendar year! So, simply change your pattern to "EEE dd MMM yyyy, h:mm:ss", and you should get the expected result:

lun. 27 dic. 2021, 3:49:08