Ginso
Ginso

Reputation: 569

java: ParseException: Unparseable date

i have a SimpleDateFormat format = new SimpleDateFormat("d M y H:m"); and i try to parse the String "8 Jan 2019 16:47" with it, but i get a ParseException. Did i create it the wrong way? According to docs.oracle.com the M should recognize 3-letter-months. Can anyone help me?

Upvotes: 0

Views: 338

Answers (2)

Anonymous
Anonymous

Reputation: 86379

java.time

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMM y H:mm", Locale.ENGLISH);

    String stringToParse = "8 Jan 2019 16:47";
    LocalDateTime dateTime = LocalDateTime.parse(stringToParse, formatter);
    System.out.println(dateTime);

The output from this snippet is:

2019-01-08T16:47

What went wrong in your code?

SimpleDateFormat and Date are poorly designed and long outdated, the former in particular notoriously troublesome. I recommend you don’t use them in 2019.

As others have said you need three M for month abbreviation (no matter if you are using the outdated SimpleDateFormat or the modern DateTimeFormatter). One M will match a month number in 1 or 2 digits, for example 1 for January.

You should also specify a locale for your formatter. I took Jan to be English so specified Locale.ENGLISH. If you don’t specify locale, the JVM’s default locale will be used, which may work well on some JVMs and suddenly break some day when the default locale has been changed or you are trying to run your program on a different computer.

Link

Oracle tutorial: Date Time explaining how to use java.time.

Upvotes: 0

Timothy T.
Timothy T.

Reputation: 1101

The official documentation: (https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)

You probably missed out this little note here:

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

Based on your example input, the following works:

SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy HH:mm");

Upvotes: 0

Related Questions