Manish Manish - 1 year ago 166
Java Question

Parsing custom date with MM/dd/yyyy hh:mm:ss zzz format in android

I have a string that represents a date with a format

MM/dd/yyyy hh:mm:ss
that looks like:

"03/26/2014 17:32:25 IST"<BR>

When I parse the string into a date as:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss zzz");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse("03/26/2014 17:32:25 IST"));
String output = sdf.parse(sdf.format(cal.getTime()));

I have tried adding
in the SimpleDateFormat but it didn't work.

Any help will be appreciated.

Answer Source

First error: You try to case a java.util.Date (the result of parse-method) on String (compile-error).

Second error: You should use pattern symbol HH not hh (twenty-four-hour-clock according to hour input of 17h).

Third error: Set the timezone on the format object, not on Calendar (and it hopefully corresponds to timezone IST - either you are in Israel or in India).

Updated: It appears that "IST" is not a known time zone name on your Android device. The motivation of Google-Android was probably to avoid ambiguous names ("Israel Standard Time" or "India Standard Time") so Android has other different names in its resource repository. You might try text preprocessing like this workaround:

if (timestampText.endsWith(" IST")) {
  timestampText = timestampText.substring(0, timestampText.length() - 4);

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
java.util.Date d = sdf.parse(timestampText);

Also check the output of method DateFormatSymbols.getInstance().getZoneStrings() in order to see if Android expects another timezone name instead of "IST" (which is more wide spread on Java-VMs).

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