Most Java application ‘java.text.SimpleDateFormat’ object is used to convert a text/string in to ‘java.util.Date’ object. Typical Parsing code would look like:
SimpleDateFormat formatter = new SimpleDateFormat(format);
ret.setLenient(false);
Date myDate = dateFormatter.parse(aStringValue)
Source for this string can come from external SORs as well, who might be running on a different timezone. Say suppose SOR is passing string “March’ 08, 2009 02:01am”. This time doesn’t exist in Pacific Time zone, because this is the hour where clocks springs forward an hour. Pacific clocks switches from 1.59 am to 3.00am directly, whereas this time exist in UTC or other non-american time zones. When your application attempts parse this string, it would get java.text.ParseException.
How to check whether your application is affected by this Problem?
In your application code base & in the dependent libraries (if possible) grep for the API “setLenient”. If there is a match and it has argument to ‘false’, then it’s quite possible that your application might be vulnerable to get java.text.ParseException.
Note: By default, SimpleDateFormat parsing is lenient. So if you don’t have setLenient() API or setLenient() API is invoked with parameter ‘true’, you don’t have to worry.
How to mitigate this problem?
Use the following mitigation strategy:
Date myDate = null;
try {
SimpleDateFormat dateFormatter = new SimpleDateFormat(format);
dateFormatter.setLenient(false);
myDate = dateFormatter.parse(aStringValue));
} catch (java.text.ParseException pEx) {
// Try parsing in UTC Format
try {
SimpleDateFormat dateFormatter = new SimpleDateFormat(format);
dateFormatter.setLenient(false);
dateFormatter.setTimeZone(TimeZone.getTimeZone(“UTC”));
dateFormatter.parse(aStringValue);
} catch (java.text.ParseException pParseEx) {
throw new DateException(pEx, aStringValue + ” : Invalid date format \n” + pEx.getMessage());
}
// If it succeeds then it’s possible timestamp could be Daylight savings time i.e. March’ 08, 2009 02:01am
// In this circumstance do Lenient parsing and return the result. It is done to
// keep behaviour backward compatible.
try {
SimpleDateFormat dateFormatter = new SimpleDateFormat(format);
dateFormatter.setLenient(true);
myDate = dateFormatter.parse(aStringValue);
} catch (java.text.ParseException pParseEx) {
throw new DateException(pEx, aStringValue + ” : Invalid date format \n” + pEx.getMessage());
}
}
In the above code, if parsing results in java.text.ParseException, then we try to parse the string in UTC timezone (non-american timezone). If String is successfully parsed, then it’s a good guarantee that String that we are trying to parse is in a Daylight savings time. In that circumstance we should parse the string with setLenient() API set to ‘true’.
Leave a Reply