Parsing dates of the format “January 10th, 2010” in Java? (with ordinal indicators, st|nd|rd|th)

This works:

String s = "January 10th, 2010";
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
System.out.println("" + dateFormat.parse(s.replaceAll("(?:st|nd|rd|th),", "")));

but you need to make sure you are using the right Locale to properly parse the month name.

I know you can include general texts inside the SimpleDateFormat pattern. However in this case the text is dependent on the info and is actually not relevant to the parsing process.

This is actually the simplest solution I can think of. But I would love to be shown wrong.

You can avoid the pitfalls exposed in one of the comments by doing something similar to this:

String s = "January 10th, 2010";
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
System.out.println("" + dateFormat.parse(s.replaceAll("(?<= \\d+)(?:st|nd|rd|th),(?= \\d+$)", "")));

This will allow you to not match Jath,uary 10 2010 for example.

Leave a Comment

tech