views:

87

answers:

1

The string I want to format looks like this: String datetime = "9/1/10 11:34:35 AM"

Following pattern for SimpleDateFormat works:

SimpleDateFormat sdf = SimpleDateFormat("M/d/yy h:mm:ss");
Date d = sdf.parse(datetime);
System.out.println(d);

Output> [Wed Sep 01 11:34:35 CEST 2010]

However I need to parse the AM/PM marker as well, and when I add that to the pattern I receive an exception.

Pattern that doesn't work:

SimpleDateFormat sdf = SimpleDateFormat("M/d/yy h:mm:ss a");

I have tried with this also with same exception:

SimpleDateFormat sdf = SimpleDateFormat("M/d/yy h:mm:ss aa");

Exception:

java.text.ParseException: Unparseable date: "9/1/10 11:34:35 AM"

I have looked through the API at http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#text but canät seem to find where I do wrong.

Any suggestions?

+1  A: 

One possibility is that your default Locale has different symbols for AM/PM. When constructing a date format you should always supply a Locale unless you really want to use the system's default Locale, e.g.:

SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy h:mm:ss a", Locale.US)
Moritz
Thanks for pointing this out. Makes sense and solved my problem.
aksamit