Reputation: 323
So, I'm trying to add AM/PM to 12:10:00
. Below is the code I'm using
SimpleDateFormat timeToString = new SimpleDateFormat("hh:mm a");
I understand hh
means 12 hours and HH
is 24 hours.
But when i put the above mentioned value in
String dateStr = timeToString.format(time);
It gives me 12:10 am
Shouldn't 00:10:00
be 12:00 am
?
EDIT:
Shouldn't 12:10
be converted to 12:10 PM
?
If yes, then how do I do it. If no, then whats the work around?
Upvotes: 1
Views: 880
Reputation: 86324
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.
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 3
Reputation: 2643
There are actually two components that you can use to display the 12 hours format:
Everything works as expected here. You now have to use the format that suits you best.
Upvotes: 0