我正在尝试确定当前区域设置是设置为12或24小时,并相应地设置am / pm。这就是我现在所拥有的,但无论是否设置为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, "");
}
答案 0 :(得分:100)
不应该是
if (!DateFormat.is24HourFormat(this))
您只想在未设置为24小时格式时分配上午/下午,对吗?
这是一个更紧凑的版本:
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, "");
}
答案 1 :(得分:8)
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);
}
答案 2 :(得分:3)
要始终以12小时格式显示AM/PM
,而不是以德语显示vorm/nachm
,请使用Locale.US
作为日期格式:
/**
* 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));
}
}
答案 3 :(得分:0)
可能与您无关,但我发现尽管这样做
DateFormat.is24HourFormat(this)
我在TextView中仍然有12个小时的版本。经过几天的玩耍,我发现某些时区,例如印度时区(+5:30 GMT),尽管将24小时制设置为ON,但仍强制使用12小时制。将其更改为Adak(格林尼治标准时间09:00)/美国时区进行了修复。