0

I know how to use SimpleDateFormat in Java. But what is the nicest way to parse all the dates which has some letters after day number? Like these: "25th May 2014", "3rd May 2014", "1st May 2014". You see how letters could be different? So I do not want to create separate formater for every number ending. Is the re a better way to do it in Java?

Ma99uS
  • 10,605
  • 8
  • 32
  • 42

1 Answers1

2

You could convert all of them to a common one using replaceAll then put that one in your single formatter string.

theDate = theDate.replaceAll("(?:(st|nd|rd|th))","xx");
if (theDate.contains("guxx"))   // Handle fixing "August" becoming "Auguxx"
    theDate = theDate.replace("guxx","gust");

This will change 1st 2nd 3rd 4th 5th to 1xx 2xx 3xx 4xx 5xx. Now you can use the static string 'xx' in your pattern.

Always Learning
  • 5,510
  • 2
  • 17
  • 34
  • 1
    What happens to Augu`st` with that regex? Does it become Auguxx? I guess the assumption is to split by spaces first and handle only the day in the date. – ThisClark Apr 29 '15 at 01:53
  • Good catch. That case is now handled with a less expensive `replace` if it happens. Thanks @ThisClark. – Always Learning Apr 29 '15 at 02:47