java.time and ThreeTen Backport
DateTimeFormatter timeFormatter
= DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String time24Hour = "12:10:00";
LocalTime time = LocalTime.parse(time24Hour);
String time12Hour = time.format(timeFormatter);
System.out.println(time12Hour);
Output from this snippet is what you expected:
12:10 PM
Notice that your format pattern string, hh:mm a
, is correct for formatting. I don’t know what you used for parsing, I suspect that your error may have been there.
I have added a locale to the formatter to control which language I get. Since AM and PM are hardly used in other languages than English, I chose Locale.ENGLISH
, but please choose the locale that is right for you.
The SimpleDateFormat
class that you used is notoriously troublesome and fortunately long outdated. Instead I am using java.time, the modern Java date and time API. This has the added bonus that parsing the 24 hour format goes smoothly without an explicit formatter. This is because the format you’ve got conforms with ISO 8601, the internation date and time standard. The modern classes parse (and also print) ISO 8601 format as their default.
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 modern 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