V6122. The 'Y' (week year) pattern is used for date formatting. Check whether the 'y' (year) pattern was intended instead.
The analyzer has detected a possible error: the 'Y' literal is used in the date formatting pattern. The 'y' specifier may have been intended.
Take a look at an example:
Date date = new Date("2024/12/31");
String result = new SimpleDateFormat("dd-MM-YYYY").format(date); //31-12-2025
The 'Y' literal in the date pattern indicates the year relative to the current week, rather than the current year.
According to the ISO-8601 standard:
- Monday is the first day of the week.
- The first week of the year must include at least four days of this year.
Look at the calendar snippet for late 2024 and early 2025:
MON |
TUE |
WED |
THU |
FRI |
SAT |
SUN |
---|---|---|---|---|---|---|
30 |
31 |
1 |
2 |
3 |
4 |
5 |
This week is the first week of the year 2025 because it complies with the standard. Therefore, if we use the 'Y' literal, we get 2025 instead of the expected 2024.
The opposite case would also be wrong:
Date date = new Date("2027/01/01");
String result =
new SimpleDateFormat("dd-MM-YYYY").format(date); // 01-01-2026
Take a look at the calendar snippet for late 2026 and early 2027:
MON |
TUE |
WED |
THU |
FRI |
SAT |
SUN |
---|---|---|---|---|---|---|
28 |
29 |
30 |
31 |
1 |
2 |
3 |
Note that January 1, 2, and 3 belong to the last week of December. The week does not comply with the standard.
To display the calendar year, use the 'y' literal in the date formatting pattern.
Here is the fixed example:
Date date = new Date("2027/01/01");
String result = new SimpleDateFormat("dd-MM-yyyy").format(date) // 01-01-2027