I am trying to parse a String to Date Object.Previously I used parse(String) definition but a date like 4/1/2004 2:00:00asasasas was getting correctly parsed which was wrong.So i used the ParsePosition signature parse(String,parsePosition) and checked if the index is not equal to the length then its an invalid Date.But above logic fails for a String as "4/1/2004 2:00:00 AM.Although it's a valid date but due to index and length logic it says invalid date when I try to parse it in "M/dd/YYYY" format. the parser parses the correct date part and does not take whole String into consideration. Any way to achieve it ? formatStr can be any format pattern.
Please advise.
public static void main(String[] args) {
String formatStr="M/dd/YYYY";
SimpleDateFormat sd = new SimpleDateFormat(formatStr, Locale.getDefault());
String str = "4/1/2004 2:00:00 AM";
ParsePosition pp1 = new ParsePosition(0);
Date retDate = sd.parse(str, pp1);
if(retDate==null ||pp1.getIndex()!=str.length() ){
System.out.println("I have a invalid Date");
}
}
yyyyrather thanYYYYmind you...M/d/y h:m:s a