Search code examples
javalocalizationjodatime

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")


Solution

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

    The only common source about such localized data is Common Locale Data Repository (CLDR), published by the 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
      }
    }