In my project I need to check if a date string evaluates to a proper Date object. I've decided to allow yyyy-MM-dd, and Date formats [(year, month, date) and (year, month, date, hrs, min)]. How can I check if they're valid ? My code returns null for "1980-01-01" and some strange dates (like 3837.05.01) whon giving a string separated by commas :
private Date parseDate(String date){
Date data = null;
// yyy-mm-dd
try {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
df.setLenient(false);
df.parse(date);
return data;
}
catch (Exception e) {
try{
int[] datArr = parseStringForDate(date);
int len = datArr.length;
// year, month, day
if(len == 3){
return new Date(datArr[0], datArr[1], datArr[2]);
}
// year, montd, day, hours, mins
else if(len ==5){
return new Date(datArr[0], datArr[1], datArr[2], datArr[3], datArr[4]);
}
// year, month, day, hours, mins, secs
else if(len == 6){
return new Date(datArr[0], datArr[1], datArr[2], datArr[3], datArr[4], datArr[5]);
}
else {
return data;
}
}
catch (Exception f){
return data;
}
}
}
private int[] parseStringForDate(String s){
String[] sArr = s.split(",");
int[] dateArr = new int[sArr.length];
for(int i=0; i< dateArr.length; i++){
dateArr[i] = Integer.parseInt(sArr[i]);
}
return dateArr;
}
I remember that I had to subtract 1900 from year date, but I also see that month is different etc, and I'd like to avoid checking every element of my array of ints from date string. Is it possible to parse them automatically in Calendar or date object ?