-6

I am trying to convert my string date: 'Saturday 19th May' to the date object. I have looked at other examples and tried to use SimpleDateFormat. The method I have at the moment is:

     DateFormat format = new SimpleDateFormat("EE/dd/MM" , Locale.ENGLISH);

However, I get this error when trying to format it.

     java.text.ParseException: Unparseable date: "Saturday 19th May" 
           (at offset 8)

Does anyone know the correct way to format this String?

Thanks.

  • 3
    Does your date string match the format `EE/dd/MM`? – Joe C Mar 17 '18 at 18:46
  • 1
    Besides the fact that your string format doesn't match the parsing format, how do you expect a date like "Saturday 19th May" to be parsed when it could occur in any number of years? – kshetline Mar 17 '18 at 18:48
  • @JoeC No, have changed it now but still do not really understand – LogitechNumberOne Mar 17 '18 at 18:55
  • @kshetline I do not need the year in my dates, does it need to have one to parse it? – LogitechNumberOne Mar 17 '18 at 18:55
  • Yes, it needs a year because a date object can't help but have a year, the result of parsing can't be ambiguous. – kshetline Mar 17 '18 at 18:56
  • 2
    "19th" is probably what's tripping it up since I don't believe `dd` handles `th`. It'd probably work if you stated `Saturday 19 May`. – Makoto Mar 17 '18 at 18:57
  • @kshetline I did not know that, thank you. – LogitechNumberOne Mar 17 '18 at 19:02
  • @Makoto okay i'll give it a go, thanks. – LogitechNumberOne Mar 17 '18 at 19:03
  • @Makoto you was correct! thank you! – LogitechNumberOne Mar 17 '18 at 19:32
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Mar 17 '18 at 21:09
  • If you just want May 19 without a year (and hence without a day-of-week even though there is one in the string), you need [the `MonthDay` class of java.time](https://docs.oracle.com/javase/9/docs/api/java/time/MonthDay.html). – Ole V.V. Mar 19 '18 at 08:25

1 Answers1

0

You can try something like this:

String str = "Saturday 17th March 2018";
DateFormat format = new SimpleDateFormat("EEE dd MMM yyyy" , Locale.ENGLISH);

System.out.println(format.parse(str.replaceAll("(?<=\\d)(st|nd|rd|th)", "")));