longwalker longwalker - 1 year ago 64
Android Question

Unparseable date: "1/29/2014 11:45:00 AM" - Android

I have a problem with parsing the following date from string: "1/29/2014 11:45:00 AM"
I do it the following way:

String source = "1/29/2014 11:45:00 AM";
Date startDate;
String sdfPattern = "MM/dd/yyyy hh:mm:ss aa";
SimpleDateFormat sdf = new SimpleDateFormat(sdfPattern, Locale.getDefault());
this.startDate = sdf.parse(source);

Interestingly, this works fine in a java project, but not in android. The error message I get:

01-15 15:36:46.950: W/System.err(2713): java.text.ParseException: Unparseable date: "1/29/2014 11:45:00 AM" (at offset 19)

Can anybody tell me what I am doing wrong?

Answer Source

Your format string specifies that you'll provide a two-digit month, but you're only providing "1".

I suspect you want:

String sdfPattern = "M/d/yyyy hh:mm:ss aa";

Additionally, the "AM/PM" designator is locale-sensitive (as are the date and time separators) . If you know that it will always use English, you should say so:

SimpleDateFormat sdf = new SimpleDateFormat(sdfPattern, Locale.US);

Unless the data is actually entered by the user (or being formatted for the user) you should avoid Locale.getDefault().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download