Reputation: 2337
I am trying to parse this "06th Oct 2013" date using java.
String[] formatStrings = {"dd MMM yyyy","dd MMMM yyyy hh:mm"};
public Date tryParse(String dateString)
{
for (String formatString : formatStrings)
{
try
{
return new SimpleDateFormat(formatString).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
I tried "ddth MMM yyyy" too it was not working.
Any idea to parse it.
Answer:
use quotes for string.
"dd'th' MMM yyyy"
Upvotes: 1
Views: 348
Reputation: 4030
Use below format along with Locale if needed
new SimpleDateFormat("dd'th' MMM YYYY");
Upvotes: 0
Reputation: 4222
Just add to your formatStrings
following pattern "dd'th' MMM yyyy"
. Well, but it won't solve problem with date like 01st Oct 2013
and 02nd Oct 2013
. You can add "dd'st' MMM yyyy"
and so one, but isn't elegant.
I'll will update this post when I solve it.
UPDATE This would be best for me:
String[] formatStrings = {"dd MMM yyyy","dd MMMM yyyy hh:mm"};
String[] forbiddenStrings = {"st","nd","rd","th"};
public Date tryParse(String dateString)
{
for(String remove : forbiddenStrings) {
dateString = dateString.replaceAll(remove,"");
}
for (String formatString : formatStrings)
{
try
{
return new SimpleDateFormat(formatString).parse(dateString);
}
catch (ParseException e) {}
}
return null;
}
Upvotes: 0
Reputation: 6909
String date = "06th Oct 2013";
date = date.substring(0,2) + date.substring(4);
That will remove the th or whatever characters in the date that's impeding the parsing.
Upvotes: 0
Reputation: 4189
You can use DateUtils, with Dateutils you can code as:
String str = "06th Oct 2013";
String[] strArrFormat = {"dd'st' MMM yyyy","dd'nd' MMM yyyy","dd'th' MMM yyyy","dd'rd' MMM yyyy"};
DateUtils tmpDU = new DateUtils();
System.out.print("" + tmpDU.parseDate(str,strArrFormat));
See also:
Upvotes: 1