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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I have written small function which detects whether current locale uses 24 or 12 hours:
Use the java.text.DateFormat class to create the correct output of the given time.
As from the API:
You just use the
getTimeInstance()
method and call theformat()
method on the returned DateFormat objectThe 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 whateverDateFormat
it returns.If you have a
SimpleDateFormat
instance in your hands, you could (if you were prepared to do a significant amount of coding) calltoPattern()
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 callapplyPattern(String)
to alter the format.