I have some old Java code that attempts to parse a string using SimpleDateFormat. It is frequently throwing a ParseException:
Non-fatal Exception: java.text.ParseException:
Unparseable date: "06:00:00 PM" at java.text.DateFormat.parse(DateFormat.java:400)
I can't see what is going wrong here. Seems simple. Hoping somebody can spot it.
public static String toTimeString(String time, String inTimeFormat, String outTimeFormat) {
DateFormat df1 = new SimpleDateFormat(inTimeFormat, Locale.getDefault());
DateFormat df2 = new SimpleDateFormat(outTimeFormat, Locale.getDefault());
String timeString = "";
try {
Date date = df1.parse(time); //<-- exception thrown here
_12HrTime = df2.format(date);
} catch (ParseException e) {
Crashlytics.recordException(e);
}
return timeString;
}
Here is how it is being called when it fails:
toTimeString("06:00:00 PM", "hh:mm:ss a", "h:mm a")
Note that the string 06:00:00 PM comes from a server response.
Every time I run this, it works correctly. But Crashlytics reports this error frequently. What am I missing??
Locale.getDefault()is going to return a value whereamaps toPM. If you are literally callingtoTimeString()with values like06:00:00 PMfor everyone, useLocale.USor something else that gives you a consistent result worldwide. "Note that the string 06:00:00 PM comes from a server response" -- um, that's messed up IMHO.Stringthat contains a date part that is not just unnecessary but even wrong? Parsing a time of day only, the value of theDatewould be completed by adding (the value of) the January 1st, 1970. I think you should not use this old Java code and write your own, much better solution/method usingjava.time, especially the classLocalTime. You can useLocale.ENGLISHfor a consistent and predictable format, butLocale.USmight do as well.LocalTimeobject, not in a string. When reading text input, parse into aLocalTimeas the first thing. Only when you need to give string output, format back into a string.