I am trying to determine if the current locale is set to 12 or 24 hour, and set am/pm accordingly. This is what I have got right now, but it shows am/pm all the time regardless if it is set to 24.
if (DateFormat.is24HourFormat(this)) { mHour = mCalendar.get(Calendar.HOUR_OF_DAY); int hourOfDay = mHour; if (hourOfDay>12) views.setTextViewText(R.id.AMPM, "pm"); if (hourOfDay==12) views.setTextViewText(R.id.AMPM, "pm"); if (hourOfDay<12) views.setTextViewText(R.id.AMPM, "am"); } else { views.setTextViewText(R.id.AMPM, ""); }
Shouldn't it be
if (!DateFormat.is24HourFormat(this))
You want to assign am/pm only when it is not set to 24 hour format, right?
Here is a more compact version:
if (!DateFormat.is24HourFormat(this)) { mHour = mCalendar.get(Calendar.HOUR_OF_DAY); int hourOfDay = mHour; if (hourOfDay >= 12) { views.setTextViewText(R.id.AMPM, "pm"); } else { views.setTextViewText(R.id.AMPM, "am"); } } else { views.setTextViewText(R.id.AMPM, ""); }
Better solution and whole code sample:
Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); // below, the "hour" and "min" are variables,to which you want to set //calendar.For example you can take this values from time picker calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, min); is24HourFormat = android.text.format.DateFormat.is24HourFormat(context); if (is24HourFormat) { // if system uses 24hourformat dateFormat will format the calender time according to 24hourformat. "HH" means 24hourformat CharSequence setTime = dateFormat.format("HH:mm", calendar); } else { // if system doesnt use 24hourformat dateFormat will format the calender time according to 12hourformat. "hh" means 12hourformat and "a" will show am/pm marker CharSequence setTime = dateFormat.format("hh:mm a", calendar); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With