Discussion
Pegasystems Inc.
JP
Last activity: 6 Nov 2024 3:07 EST
Do not use YYYY (uppercase) in Java date formatting
Hi,
At the end of year 2021, with the new year just around the corner, my customer was shocked to find an odd behavior of out-of-the-box @CurrentDate fuction. System returned "20221226" for 26th of December in 2021, while customer was expecting "20211226". In this post, I am sharing the issue and how to avoid confusion.
- How to replicate the issue
1. When a year is coming to a close, try using @CurrentDate(YYYYMMdd, "Asia/Tokyo"). In this particular example, I am running this on the 26th of December, 2021.
2. System returns "20221226", against our expecations. This is one year ahead! Weird, isn't it?
- "yyyy" vs "YYYY"
This lowercase vs uppercase in date formatting is not a Pega-specific issue, but a general topic to Java. Java 7 introduced "YYYY" as a new date pattern to identify the date week year. An average year is 52.1775 weeks long, which means that a year might have either 52 or 53 weeks considering indivisible weeks. Using "YYYY" unintendedly while formatting a date could cause severe issues in your Java application. First, let's look at the calendar of December, 2021.
Now, below is a result when I tested on respective day.
No | Operating System Date | Returned Date | Correct? |
---|---|---|---|
1 | 1st of November, 2021 | "20211101" | Correct |
2 | 1st of December, 2021 | "20211201" | Correct |
3 | 25th of December, 2021 | "20211225" | Correct |
4 | 26th of December, 2021 | "20221226" | Incorrect |
5 | 27th of December, 2021 | "20221227" | Incorrect |
6 | 28th of December, 2021 | "20221228" | Incorrect |
7 | 29th of December, 2021 | "20221229" | Incorrect |
8 | 30th of December, 2021 | "20221230" | Incorrect |
9 | 31st of December, 2021 | "20221231" | Incorrect |
10 | 1st of January, 2022 | "20220101" | Correct |
11 | 2nd of January, 2022 | "20220102" | Correct |
As you can see, the reason for this odd behavior is the week that the 26th - 31th of December 2021 falls in technically is the first week of 2022. In summary, "yyyy" represents the calendar year whereas "YYYY" represents the year of the week, used in the ISO year-week calendar. In most cases, "yyyy" and "YYYY" yield the same number, however they may be different. That’s a subtle difference that only causes problems around a year change so your code could have been running perfectly fine all year around only to cause a problem in the new year. This issue can be a pain to notice and debug. In general, you should almost always (in 99% of use cases) use the calendar year - "yyyy". In my opinion, this new specification post Java 7 is very confusing, and I would advise you to add some form of linting or checking to make sure your code does not have any date formats referencing "YYYY".
Hope this helps.
Thanks,