Suspicious date format¶
ID: java/suspicious-date-formatKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - correctnessQuery suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
The JavaSimpleDateFormat class provides many placeholders so that you can define precisely the date format required. However, this also makes it easy to define a pattern that doesn’t behave exactly as you intended. The most common mistake is to use theY placeholder (which represents the ISO 8601 week year), rather thany (which represents the actual year). In this case, the date reported will appear correct until the end of the year, when the “week year” may differ from the actual year.
Recommendation¶
Ensure the format pattern’s use ofY is correct, and if not replace it withy.
Example¶
The following example uses the date formatYYYY-MM-dd. On the 30th of December 2019, this code will output “2020-12-30”, rather than the intended “2019-12-30”.
System.out.println(newSimpleDateFormat("YYYY-MM-dd").format(newDate()));
The correct pattern in this case would beyyyy-MM-dd instead ofYYYY-MM-dd.
References¶
Java API Specification:SimpleDateFormat.