user3555472
user3555472

Reputation: 836

Android 12 hours Time Format getting wrong

I am using

DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy hh:mm a");
String dateAsString = dateFormat.format(gmt);

And getting String 06-06-2017 08:15 a.m. Why I am getting a.m. instated of AM or PM?

Upvotes: 0

Views: 230

Answers (2)

Anonymous
Anonymous

Reputation: 86296

It depends on the locale. If you use SimpleDateFormat (which you may not want to do, see below), I recommend you give it an explicit locale. The one you construct uses the device’s default, which explains why you get different results on different devices. If you want that, use new SimpleDateFormat("MM-dd-yyyy hh:mm a", Locale.getDefault()) so the reader knows you have thought about it. To make sure you get AM and PM, use for example new SimpleDateFormat("MM-dd-yyyy hh:mm a", Locale.ENGLISH).

Why would you not want to use SimpleDateFormat? I consider it long outdated since the much better replacement for the Java 1.0 and 1.1 classes came out with Java 8 in 2014. They have also been backported to Android Java 7 in the ThreeTenABP. Get this and write for example:

    LocalDateTime gmt = LocalDateTime.of(2017, Month.JUNE, 6, 8, 15);
    DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("MM-dd-uuuu hh:mm a",
                                                                   Locale.ENGLISH);
    String dateAsString = gmt.format(dateTimeFormat);

The result is

06-06-2017 08:15 AM

To make explicit that the time is in GMT, you may use an OffsetDateTime with offset ZoneOffset.UTC.

Link: How to use ThreeTenABP in Android Project.

Upvotes: 2

Suraj Makhija
Suraj Makhija

Reputation: 1396

The AM/PM/a.m. actually depends on the device. Try the same code on other devices and you might get to see a different result. If you need AM/PM only, then you need to do it manually by replacing the dots and converting it to uppercase.

Upvotes: 2

Related Questions