New Simpledateformat("hh:mm A", Locale.getdefault()).parse("04:30 Pm") Giving Unparseable Exception
Solution 1:
Offset 6 of your string is where it says PM
.
It’s a locale issue. AM
and PM
, although derived from Latin are called that in English, not in very many other languages. Therefore those abbreviations are not recognized in very many locales. In your code you use Locale.getDefault()
, and if it returns a non-English-speaking locale, you are likely to get the error. Try for example Locale.ENGLISH
instead. Alternatively make sure you get a string in the right format and language for the default locale.
java.time
If you are doing any considerable work with times or dates in your app, and also for anyone programming for Java 8 or later or for Android API level 26 or higher: The classes you use, Date
and SimpleDateFormat
, have always had design problems, the latter in particular is typically troublesome. Fortunately both are long outdated now and replaced by java.time, the modern Java date and time API. So use this instead:
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
LocalTimetime= LocalTime.parse("04:30 PM", timeFormatter);
System.out.println(time);
Output:
16:30
A LocalTime
is a time of day without date and without time zone and seems to match your need much better than the old-fashioned Date
class.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links
- Oracle tutorial: Date Time explaining how to use
java.time
. - Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Post a Comment for "New Simpledateformat("hh:mm A", Locale.getdefault()).parse("04:30 Pm") Giving Unparseable Exception"