如何检查系统是12小时还是24小时?
我试图确定当前的语言环境是否设置为12或24小时,并相应地设置上午/下午。 这是我现在所知道的,但无论它是否设置为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, ""); }
不应该是
if (!DateFormat.is24HourFormat(this))
只有当它没有设置为24小时格式时,你才想要指定am / pm,对吗?
这是一个更紧凑的版本:
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, ""); }
更好的解决scheme和整个代码示例
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); android.text.format.DateFormat dateFormat = new android.text.format.DateFormat(); is24HourFormat= dateFormat.is24HourFormat(this); 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); }
要以12小时格式显示AM/PM
,而不是像vorm/nachm
,请使用Locale.US
作为date格式:
/** * Returns the time in a localized format. The 12-hours format is always displayed with * AM/PM (and not for example vorm/nachm in german). * * @param context the context * @return Localized time (15:24 or 3:24 PM). */ public static String getTime(Context context, long time) { if (android.text.format.DateFormat.is24HourFormat(context)) { return new SimpleDateFormat("HH:mm", Locale.US).format(new Date(time)); } else { return new SimpleDateFormat("hh:mm a", Locale.US).format(new Date(time)); } }