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?
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.
DateFormat.getTimeInstance(...)
DateFormat
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.
SimpleDateFormat
toPattern()
applyPattern(String)
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);
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
getTimeInstance()
format()
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; } }