I have the following code for parsing dates:
public Boolean isDate(String date, String dateFormat) {
try {
DateTimeFormat.forPattern(dateFormat).parseDateTime(date);
} catch(Exception e) {
return false;
}
return true;
}
This works well with more recent dates like 20071001
with format yyyyMMdd
. However for dates earlier than 1970, like 19600101
with the same format of yyyyMMdd
, the method returns false.
Any ideas on how I can sort this out will be appreciated very much.
UPDATE:
The exception I get is:
Cannot parse "19400101": Illegal instant due to time zone offset transition (Africa/Nairobi)
And this is how I'm calling the method:
if(validationUtils.isDate(propVal, dateFormat) == false) {
String msg = "Not a valid DATE";
Quartet<String, String, String, String> t = new Quartet<String, String, String, String>(recNo, field, propVal, msg);
errors.add(t);
}
The class containing the isDate
method is a bean which I wire using @Autowired IValidationUtils validationUtils
. This is not the only validation I'm doing. Other validation stuff succeeds, and this, among others has led me to the conclusion that the issue is with Joda Time.
UPDATE (SOLUTION):
Following @Ettiene's suggestion (in the answer below), I got a solution to my issue. Revised working code is:
public Boolean isDate(String date, String dateFormat) {
try {
DateTimeFormatter fmt = DateTimeFormat.forPattern(dateFormat);
DateTime dt = fmt.withZone(DateTimeZone.UTC).parseDateTime(date);
} catch(Exception e) {
return false;
}
return true;
}