javaandroiddatedatetimedate-parsing

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.setTimeZone(TimeZone.getDefault());
cal.setTime(sdf.parse("03/26/2014 17:32:25 IST"));
String output = sdf.parse(sdf.format(cal.getTime()));

While parsing the date in Android using sdf.Parse, I get an exception as java.text.ParseException: Unparseable date: "03/26/2015 17:32:25 IST" (at offset 20). Any idea??

I have tried adding Locale.getDefault() in the SimpleDateFormat but it didn't work.

Any help will be appreciated.


Solution

  • 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");
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    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).