I am a French Android developer, so using Locale.getDefault()
causes my DateFormat
to use a 24-hour mode. But, when I set manually my device to 12-hour mode via the setting menu, DateFormat
keeps going in a 24-hour format.
On the contrary, TimePicker
s are set according to my own 12/24-hour setting.
Is there any way to make DateFormat
s behave the same way as TimePicker
s ?
EDIT:
Here is my DateFormat
declaration:
timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
And here is where I set my TimePicker
to 12 or 24-hour mode.
tp.setIs24HourView(android.text.format.DateFormat.is24HourFormat((Context) this));
My Solution:
According to @Meno Hochschild's answer below, here is how I solved this tricky problem:
boolean is24hour = android.text.format.DateFormat.is24HourFormat((Context) this);
tp.setIs24HourView(is24hour); // tp is the TimePicker
timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
if (timeFormat instanceof SimpleDateFormat) {
String pattern = ((SimpleDateFormat) timeFormat).toPattern();
if (is24hour) {
timeFormat = new SimpleDateFormat(pattern.replace("h", "H").replace(" a",""), Locale.getDefault());
}
else {
timeFormat = new SimpleDateFormat(pattern.replace("H", "h"), Locale.getDefault());
}
}
After this, timeFormat
will correctly format dates whether your device is set to display times in a 24-hour format or in a 12-hour one. And the TimePicker
will be correctly set too.
SimpleDateFormat
, but aDateFormat
. Just edited to correct this. – Weakling