Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if a locale uses AM/PM?

I have a label displaying only the minutes part of a certain hour of the day. I want it to read "PM" or "00", depending on time zone.

My current solution simply uses Joda's DateTimeFormat.shortTime().withLocale(myLocale) and takes the last 2 characters from the result. This works, but feels wrong.

Instead, I want to check if the given locale uses AM/PM notation, but I haven't found an API call to give me that information. Does it exist, either in JodaTime or the Java libraries themselves? For example, I would like to write something like usesAmPm(myLocale)) ? DateTimeFormat.forPattern("a") : DateTimeFormat.forPattern("mm")

like image 365
Jorn Avatar asked Nov 29 '13 10:11

Jorn


1 Answers

Answer to the question how to check if a given locale uses AM/PM notation:

The only common source about such localized data is CLDR from Unicode consortium. Indirectly the JDK loads a small subset of CLDR which can be accessed as follows:

public static boolean usesAmPm(Locale locale) {
  DateFormat df = DateFormat.getTimeInstance(DateFormat.FULL, locale);
  if (df instanceof SimpleDateFormat) {
    return ((SimpleDateFormat) df).toPattern().contains("a");
  } else {
    return false; // unlikely to happen
  }
}
like image 185
Meno Hochschild Avatar answered Sep 18 '22 06:09

Meno Hochschild