Skip to content

Commit 8814629

Browse files
committed
Java: Add a query for suspicious date format patterns.
1 parent 816a8d1 commit 8814629

3 files changed

Lines changed: 56 additions & 0 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
System.out.println(new SimpleDateFormat("YYYY-MM-dd").format(new Date()));
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
6+
7+
<overview>
8+
<p>
9+
Some <code>SimpleDateFormat</code> patterns might not work correctly at the end of the calendar
10+
year, due to use of the <code>Y</code> placeholder (representing the ISO 8601 week year), rather
11+
than <code>y</code> representing the actual year.
12+
</p>
13+
</overview>
14+
15+
<recommendation>
16+
<p>
17+
Ensure the format pattern's use of <code>Y</code> is correct, and if not replace it with <code>y</code>.
18+
</p>
19+
</recommendation>
20+
21+
<example>
22+
<p>
23+
The following example uses the date format <code>YYYY-MM-dd</code>.
24+
On the 30th of December 2019, this code will output "2020-12-30", rather than the intended "2019-12-30".
25+
</p>
26+
<sample src="SuspiciousDateFormat.java" />
27+
</example>
28+
29+
<references>
30+
<li>
31+
Java Platform, Standard Edition 7, API Specification:
32+
<a href="https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>.
33+
</li>
34+
</references>
35+
36+
</qhelp>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @name Suspicious date format
3+
* @description Some date format patterns don't work as they might seem.
4+
* @kind problem
5+
* @problem.severity warning
6+
* @precision high
7+
* @id java/suspicious-date-format
8+
* @tags correctness
9+
*/
10+
11+
import java
12+
13+
from ConstructorCall c, string format
14+
where
15+
c.getConstructedType().hasQualifiedName("java.text", "SimpleDateFormat") and
16+
format = c.getArgument(0).(StringLiteral).getValue() and
17+
format.matches("%Y%") and
18+
format.matches("%M%")
19+
select c, "Date formatter is passed a suspicious pattern \"" + format + "\"."

0 commit comments

Comments
 (0)