How do I find out whether a locale uses 12 or 24 h

2019-02-13 09:03发布

In Java, I want to print just the time of day in hours and minutes and want it to correctly switch between, e.g., "13:00" and "1:00 PM" according to the locale. How do I do this?

标签: java time locale
3条回答
ら.Afraid
2楼-- · 2019-02-13 09:06

I have written small function which detects whether current locale uses 24 or 12 hours:

public static boolean is24HourLocale() {
    String output = SimpleDateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());
    if (output.contains(" AM") || output.contains(" PM")) {
        return false;
    } else {
        return true;
    }
}
查看更多
混吃等死
3楼-- · 2019-02-13 09:16

Use the java.text.DateFormat class to create the correct output of the given time.

As from the API:

To format a date for the current Locale, use one of the static factory methods:

myString = DateFormat.getDateInstance().format(myDate);

You just use the getTimeInstance() method and call the format() method on the returned DateFormat object

查看更多
成全新的幸福
4楼-- · 2019-02-13 09:18

The locale doesn't explicitly specify whether 12 or 24 hour time formats are preferred. Rather, locale specific date formats are handled by the locale defining the formats directly.

  • If you simply want to use the "locale preferred" time format, just call one of the three DateFormat.getTimeInstance(...) static methods, and use whatever DateFormat it returns.

  • If you have a SimpleDateFormat instance in your hands, you could (if you were prepared to do a significant amount of coding) call toPattern() and parse the resulting pattern to see if it used a 12 or 24 hour dates ... or neither. You could even tweak the pattern to use the "other" form and then call applyPattern(String) to alter the format.

查看更多
登录 后发表回答