-2

I tried to change string,which looks like this : 4th of July 2016

The code I tried to run is:

        Date d = null;
        String[] formats = {"d'st of' MMMMM yyyy","d'nd of' MMMMM yyyy","d'rd of' MMMMM yyyy","d'th of' MMMMM yyyy"};
        for (String format : formats) {
            try {
                d = new SimpleDateFormat(format).parse(date);
            }
            catch (Exception e){
                System.out.println("Error in ConvertStringToDate s" + e);
            } 
        }
System.out.print(d.toString());

The error I was getting from the console:

Error in ConvertStringToDate sjava.text.ParseException: Unparseable date: "4th of July 2016"
Error in ConvertStringToDate sjava.text.ParseException: Unparseable date: "4th of July 2016"
Error in ConvertStringToDate sjava.text.ParseException: Unparseable date: "4th of July 2016"
Error in ConvertStringToDate sjava.text.ParseException: Unparseable date: "4th of July 2016"
Exception in thread "main" java.lang.NullPointerException
    at MatchData.CollectMatch(MatchData.java:113)
    at GetData.main(GetData.java:13)

Thank ahead to anyone who tries to help :)

DoronK
  • 3
  • 3
  • 2
    The code you've presented wouldn't loop over all the formats - it would die with a NullPointerException in the *first* iteration, as you're missing a brace. Please provide a [mcve] of the code you're actually running. – Jon Skeet Jul 05 '16 at 06:58
  • 1
    Next, which locale are you in? You haven't specified a locale, so it'll be using your system default. If you specify `Locale.ENGLISH` when you create the `SimpleDateFormat` you may well find that fixes it... – Jon Skeet Jul 05 '16 at 07:00
  • 1
    @JonSkeet Thanks,I was missing the locale.and adding it solved the problem. – DoronK Jul 05 '16 at 07:07

1 Answers1

0

Just get rid of all st of, nd of, rd of and th of using String.replace, and parse the date using d MMMMM yyyy.

new SimpleDateFormat(format).parse(
    date.replace("st of", "")
        .replace("nd of", "")
        .replace("rd of", "")
        .replace("th of", "")
);
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115