Skip to content

Commit e651112

Browse files
committed
Fix date string parsing in JSON.nullableDate().
1 parent 5a28491 commit e651112

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

psicashlib/src/main/java/ca/psiphon/psicashlib/PsiCashLib.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1675,18 +1675,23 @@ private static Date nullableDate(JSONObject json, String key) throws JSONExcepti
16751675
Date date;
16761676

16771677
// We need to try different formats depending on the presence of milliseconds.
1678-
SimpleDateFormat isoFormatWithMS = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'", Locale.US);
1678+
// Note that we are setting parsing mode to strict (`setLenient(false)`) since
1679+
// lenient parsing may produce incorrect output if the input date string is
1680+
// not formatted exactly as expected.
1681+
SimpleDateFormat isoFormatWithMS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
16791682
isoFormatWithMS.setTimeZone(TimeZone.getTimeZone("UTC"));
1683+
isoFormatWithMS.setLenient(false);
16801684
try {
16811685
date = isoFormatWithMS.parse(dateString);
16821686
} catch (ParseException e1) {
1683-
SimpleDateFormat isoFormatWithoutMS = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'", Locale.US);
1687+
SimpleDateFormat isoFormatWithoutMS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
16841688
isoFormatWithMS.setTimeZone(TimeZone.getTimeZone("UTC"));
1689+
isoFormatWithMS.setLenient(false);
16851690
try {
16861691
date = isoFormatWithoutMS.parse(dateString);
16871692
} catch (ParseException e2) {
16881693
// Should not happen. No way to recover.
1689-
throw new JSONException("Failed to parse date with key " + key + "; error: " + e2.toString());
1694+
throw new JSONException("Failed to parse date with key " + key + "; error: " + e2);
16901695
}
16911696
}
16921697

0 commit comments

Comments
 (0)