Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if Locale is using 12 or 24 hours format? [duplicate]

I'm trying to know if, from the Locale, I have to use the 24 or the 12 format.

I found this:

if (android.text.format.DateFormat.is24HourFormat(getApplicationContext()))

But this returns a boolean according to the system, not to the Locale. This means that if the user use english for the app but has a phone using the 24hours format, it will return true...

How can I get a boolean telling me if the format to use is, or not, 24hours? I'm not using Joda. Thanks in advance.

EDIT as it seems that some people think that's a duplicate, I already read the posts you provided as a source for the duplicate flag. It was only solved with approximated workarounds or method providing a date, most of the time the current one, even if it's in the corresponding format.

As you can guess, if I'm asking for a way to know whether I should use the 12 hours format or not according to the Locale, it means that I don't need the date or anything, that I already have, but a confirmation about the format I have to use.

like image 683
Virthuss Avatar asked Jan 06 '16 08:01

Virthuss


1 Answers

Taking a look at the source code of the actual android.text.format.DateFormat.is24HourFormat method you'll see how they do it:

    Locale locale = context.getResources().getConfiguration().locale;

    java.text.DateFormat natural =
        java.text.DateFormat.getTimeInstance(
            java.text.DateFormat.LONG, locale);

    if (natural instanceof SimpleDateFormat) {
        SimpleDateFormat sdf = (SimpleDateFormat) natural;
        String pattern = sdf.toPattern();
        if (pattern.indexOf('H') >= 0) {
            value = "24";
        } else {
            value = "12";
        }
    } else {
        value = "12";
    }

So you can adapt it to the way you get the locale.

like image 164
carrizo Avatar answered Nov 18 '22 19:11

carrizo