Reputation: 21025
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
Reputation: 86324
While the other answers are correct but outdated and since this question is still being visited, here is the modern answer.
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.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.uuuu
versus yyyy
in DateTimeFormatter
formatting pattern codes in Java?java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 1
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
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
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
Reputation: 159844
Use something like:
DateFormat sdf = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
Date date = sdf.parse("6 Aug 2012");
Upvotes: 1