5

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?

a_horse_with_no_name
  • 440,273
  • 77
  • 685
  • 758
Chen Kinnrot
  • 19,385
  • 15
  • 74
  • 132

5 Answers5

9

You need to mention the Locale as well...

Date date = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH).parse("6 Aug 2012");
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
Bharat Sinha
  • 12,727
  • 6
  • 35
  • 63
1

Use something like:

DateFormat sdf = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
Date date = sdf.parse("6 Aug 2012");
Reimeus
  • 152,723
  • 12
  • 195
  • 261
1

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");
Jesus Rodriguez
  • 11,660
  • 9
  • 59
  • 86
Durgadas Kamath
  • 400
  • 2
  • 11
1

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]);
Kumar Vivek Mitra
  • 32,278
  • 6
  • 43
  • 74
1

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

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117