0

I am a beginner and i want to convert this String into a Date Instance. Why get i an unparsable Exception ? Can anyone help me ?

String s=  "2020 Mar 11 11:09:42";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy MMM d HH:mm:ss");
Date parsedDate =  formatter.parse(s);
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 05 '21 at 13:15
  • 1
    @celikler_data there is nothing wrong with your code. I just executed it since I didn't see any errors in it. It works just fine. What error do you get, exactly? Maybe the message that there is a possible exception you don't throw or catch? – Stultuske Nov 05 '21 at 13:19
  • @Stultuske There is something wrong with the code. It does not specify the locale to be used for parsing. Not all languages have a month that is abbreviated `Mar`. – Ole V.V. Nov 05 '21 at 13:20
  • i get this error message: Exception in thread "main" java.text.ParseException: Unparseable date: "2020 Mar 11 11:09:42" –  Nov 05 '21 at 13:21
  • 1
    @celikler_data Ole is on to something. What language is your system in? – Stultuske Nov 05 '21 at 13:22
  • We mean, the default language of your JVM, is it English, Turkish or something else? (It probably picks up a default language from the OS, not guaranteed.) – Ole V.V. Nov 05 '21 at 13:24
  • my system language is german.. –  Nov 05 '21 at 13:27
  • Thank you so much it works now i changed the month –  Nov 05 '21 at 13:27
  • 1
    the reason of the error was the system language :)) –  Nov 05 '21 at 13:28
  • 1
    I still recommend that you switch to java.time. Use `LocalDateTime parsedDate = LocalDateTime.parse(s, DateTimeFormatter.ofPattern("u MMM d HH:mm:ss", Locale.ENGLISH));` (still remembering to specify locale). It yields `2020-03-11T11:09:42`. – Ole V.V. Nov 05 '21 at 13:33
  • 2
    [Never use SimpleDateFormat or DateTimeFormatter without a Locale](https://stackoverflow.com/a/65544056/10819573). – Arvind Kumar Avinash Nov 05 '21 at 13:36

0 Answers0