Varun Barve
Varun Barve

Reputation: 323

SimpleDateFormat AM/PM conversion

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

Answers (2)

Anonymous
Anonymous

Reputation: 86324

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

Upvotes: 3

Iulian Popescu
Iulian Popescu

Reputation: 2643

There are actually two components that you can use to display the 12 hours format:

  • K for "Hour in am/pm (0-11)" -> will display: 00:50 PM
  • h for "Hour in am/pm (1-12)" -> will display: 12:50 PM

Everything works as expected here. You now have to use the format that suits you best.

Upvotes: 0

Related Questions