I have a string which can possibly contain a date in any of the following formats:
2001-01-05 (yyyy-mm-dd)
2001/01/05 (yyyy/mm/dd)
01/05/2001 (dd/mm/yyyy)
01-05-2001 (dd-mm-yyyy)
2001 january 5
2001 5 january
january 5 2001
5 january 2001
january 5
5 january
I want to be able to parse the particular string and extract the Date object from it.
My approach was as follows:
String[] date_formats = {
"yyyy-MM-dd",
"yyyyy/MM/dd",
"dd/MM/yyyyy",
"dd-MM-yyyy",
"yyyy MMM dd",
"yyyy dd MMM",
"dd MMM yyyy",
"dd MMM",
"MMM dd",
"dd MMM yyyy"};
String output_date = null;
for (String formatString : date_formats)
{
try
{
Date mydate = new SimpleDateFormat(formatString).parse(token);
SimpleDateFormat outdate = new SimpleDateFormat("yyyyMMdd");
output_date = outdate.format(mydate);
break;
}
catch (ParseException e) {
System.out.println("Next!");
}
}
This doesn't seem to work as expected. Especially for dates like 5 January 2001 etc. How do I go about doing this?
new SimpleDateFormat("{format}", Locale.ENGLISH);)This doesn't seem to work as expected. Do you get an exception or a date which does not seems good? An example would be appreciated.