Good afternoon, I read the following line from the file, trying to convert to type Date. Does not work. Tell me, please, what is the error.

String dat ="Sat Jan 03 19:47:23 MSK 1984"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); simpleDateFormat.applyPattern("EEE MMM dd HH:mm:ss zzz yyyy"); Date birthDate = simpleDateFormat.parse(dat); 

Throws out such an error:

 Exception in thread "main" java.text.ParseException: Unparseable date: "Sat Jan 03 19:47:23 MSK 1984" at java.text.DateFormat.parse(DateFormat.java:366) 
  • Specify what does not work. Throws an error, does not compile, or is the received date different from the expected one? - Yuriy SPb
  • Exception in thread "java.text.ParseException: Unparseable date:" Sat Jan 03 19:47:23 MSK 1984 "at java.text.DateFormat.parse (DateFormat.java.0666) - Alexander
  • 2
    And if so: SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); ? - Yuriy SPb
  • Probably a stupid question, why is the second parameter required? - Alexander
  • The question is normal) Apparently because you have a Russian system locale, and the date string locale is Anglo-Saxon. - Yuriy SPb

3 answers 3

It's all about locale :

 String dat ="Sat Jan 03 19:47:23 MSK 1984"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); Date birthDate = simpleDateFormat.parse(dat); 

    Try this:

     String str = "Sat Jan 03 19:47:23 MSK 1984"; DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); Date date = format.parse(str); 

    As StateItPrimitive and Yuriy SPb correctly said, the date parsing takes into account the locale.

    • Maybe StateItPrimitive said correctly, but it seems you responded 2 seconds earlier (in the first minute seconds were written)! :) - StateItPrimitive
    • @StateItPrimitive, and my comment was another 10 seconds before your answer) - YuriySPb
    • @ YuriySPb Yes, I didn’t look at the comments :( - StateItPrimitive
    • @StateItPrimitive, not scary) I wrote in the comment, because I wasn't sure if the case was exactly in the locale) - YuriySPb

    In addition to the above, you can also add that there is a ParseExact method that analyzes a string according to a certain pattern.