KB Article #180779

Groovy seems to give the wrong year when using "YYYY" as the year code

Problem

Groovy dates seem to give the wrong year when using the code YYYY for the year.


Resolution

Groovy uses the code YYYY for the ISO week numbering year. You should use the code yyyy unless you specifically want the ISO week numbering year for some application. The following Groovy fragment can be run online in the Groovy playground to illustrate the difference between yyyy and YYYY:


dt = new Date().parse("MM-dd-yyyy","12-25-2019")
(0..6).each() {
  println "dt=" + dt \
    + " wrong=" + dt.format("YYYYMMdd HH:mm:ss.SSS") \
    + " right=" + dt.format("yyyyMMdd HH:mm:ss.SSS")
  dt += 1
}


That code gives the following output:


dt=Wed Dec 25 00:00:00 WIB 2019 wrong=20191225 00:00:00.000 right=20191225 00:00:00.000
dt=Thu Dec 26 00:00:00 WIB 2019 wrong=20191226 00:00:00.000 right=20191226 00:00:00.000
dt=Fri Dec 27 00:00:00 WIB 2019 wrong=20191227 00:00:00.000 right=20191227 00:00:00.000
dt=Sat Dec 28 00:00:00 WIB 2019 wrong=20191228 00:00:00.000 right=20191228 00:00:00.000
dt=Sun Dec 29 00:00:00 WIB 2019 wrong=20201229 00:00:00.000 right=20191229 00:00:00.000
dt=Mon Dec 30 00:00:00 WIB 2019 wrong=20201230 00:00:00.000 right=20191230 00:00:00.000
dt=Tue Dec 31 00:00:00 WIB 2019 wrong=20201231 00:00:00.000 right=20191231 00:00:00.000 


You can see how the ISO week numbering year is "2020" for Dec 29, 2019 and later. That is the correct ISO week numbering year, but when incorrectly used in a date string like this, it shows a date that is a year off.