8

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

3 Answers 3

6

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
  }
}
6

This is very similar to Meno's answer, but I didn't like the instanceof usage (some form of OCD, I guess). Here's my version:

public static boolean usesAmPm(Locale locale)
{
    String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        FormatStyle.MEDIUM, FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);
    return pattern.contains("a");
}
0
1

A shortened variant of Meno's solution:

public static boolean usesAmPm(Locale locale) {
        DateFormat df = DateFormat.getTimeInstance(DateFormat.FULL, locale);
        return df instanceof SimpleDateFormat && ((SimpleDateFormat) df).toPattern().contains("a");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.