How to find out if the locale uses 12 or 24 hours in Java?

In Java, I want to print only the time of day in hours and minutes, and I want it to switch correctly between, for example, β€œ13:00” and β€œ1:00 PM” in accordance with the locale. How to do it?

+6
java time locale
source share
3 answers

The locale does not explicitly indicate whether 12 or 24 hour time formats are preferred. Rather, language date formats are handled by a locale that defines formats directly.

  • If you just want to use the time format selected by language, just call one of the three DateFormat.getTimeInstance(...) static methods and use any DateFormat that it returns.

  • If you have an instance of SimpleDateFormat in your hands, you can (if you were ready to do a significant part of the coding) call toPattern() and analyze the resulting template to see if it used 12 or 24 hour dates ... or not. You can even configure the template to use a β€œdifferent” form, and then call applyPattern(String) to change the format.

+4
source share

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

How from the API:

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

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

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

+4
source share

I wrote a small function that determines if the 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; } } 
+1
source share

All Articles