Chen Kinnrot
Chen Kinnrot

Reputation: 21025

Getting a weird exception Unparseable date: "6 Aug 2012"

I got a date time format - "dd MMM yyyy", when trying to parse "6 Aug 2012", I get an java.text.ParseException Unparseable date.

Every thing looks fine, do you see the problem?

Upvotes: 5

Views: 1773

Answers (5)

Anonymous
Anonymous

Reputation: 86324

While the other answers are correct but outdated and since this question is still being visited, here is the modern answer.

java.time and ThreeTenABP

Use java.time, the modern Java date and time API, for your date work. This will work with your Android version/minSDK:

    DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("d MMM uuuu", Locale.ENGLISH);

    String str = "6 Aug 2012";
    LocalDate date = LocalDate.parse(str, dateFormatter);
    System.out.println(date);

Output:

2012-08-06

In the format pattern java.time uses just one d for either one or two digit day of month. For year you may use either of yyyy, uuuu, y and u. And as the others have said, specify locale. If Aug is English, then an English-speaking locale.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Upvotes: 1

Bharat Sinha
Bharat Sinha

Reputation: 14363

You need to mention the Locale as well...

Date date = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH).parse("6 Aug 2012");

Upvotes: 9

Durgadas Kamath
Durgadas Kamath

Reputation: 390

This should work for you. You will need to provide a locale

Date date = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH).parse("6 Aug 2012");

Or

Date date = new SimpleDateFormat("dd MMM yyyy", new Locale("EN")).parse("6 Aug 2012");

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

Use the split() function with the delimiter " "

String s = “6 Aug 2012”;

String[] arr = s.split(" ");

int day = Integer.parseInt(arr[0]);
String month = arr[1];
int year = Integer.parseInt(arr[2]);

Upvotes: 1

Reimeus
Reimeus

Reputation: 159844

Use something like:

DateFormat sdf = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
Date date = sdf.parse("6 Aug 2012");

Upvotes: 1

Related Questions