Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat - Unparseable date

I try to convert String to Date.

Here is my code:

    SimpleDateFormat format =  new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    Date date = format.parse("Sun Apr 08 16:37:00 CEST 2012");

I get exception:

04-08 13:51:36.536: W/System.err(8005): java.text.ParseException: Unparseable date: "Sun Apr 08 16:37:00 CEST 2012".

Format seems to be ok. Am I missing something?

Thanks.

like image 913
Domiik Avatar asked Apr 08 '12 11:04

Domiik


People also ask

How do I change date format in SimpleDateFormat?

Create Simple Date Format // Date Format In Java String pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); According to the example above, the String pattern will be used to format dates, and the output will be shown as "yyyy-MM-dd".

Is SimpleDateFormat deprecated?

Is SimpleDateFormat deprecated? Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

How do you handle Unparseable date exception in Java?

Basically, this exception occurs due to the input string is not correspond with the pattern. You can try the below format: SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.

Why is SimpleDateFormat not thread-safe?

2.2.Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. So SimpleDateFormat instances are not thread-safe, and we should use them carefully in concurrent environments.


2 Answers

Either the code you posted is not your actual code, or you have a locale issue. It works fine on Sun Oracle Java 1.6 with a US locale.

Change your code to:

SimpleDateFormat format =  
    new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
like image 103
Brian Roach Avatar answered Oct 05 '22 23:10

Brian Roach


SimpleDateFormat is Locale specific. At least the pattern E and M are locale specific, because for example "Sun" or "Sunday" will not match for Locale.GERMAN or Locale.FRENCH etc. You better specify the used Locale

SimpleDateFormat format =  new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);

or use a format, which is not locale specific.

like image 37
Michael Konietzka Avatar answered Oct 05 '22 23:10

Michael Konietzka