在开发中会涉及到对12小时和24小时的切换,查阅资料终于找到解决方案,代码如下:
1.获取当前小时制:
private String getTimeformat(){
return Settings.System.getString(mContext.getContentResolver(),
Settings.System.TIME_12_24);
}
2.切换时区
Settings.System.putString(mContext.getContentResolver(),
Settings.System.TIME_12_24,
isChecked ? "24" : "12");
Intent timeChanged = new Intent(Intent.ACTION_TIME_CHANGED);
int timeFormatPreference =
isChecked ? Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR
: Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR;
timeChanged.putExtra(Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, timeFormatPreference);
mContext.sendBroadcast(timeChanged);
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateTimeAndDateDisplay(mContext);
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
mContext.registerReceiver(mIntentReceiver, filter);
private void updateTimeAndDateDisplay(Context context) {
String format = getTimeformat();
final Calendar now = Calendar.getInstance();
String dateform="";
if(!TextUtils.isEmpty(format)) {
if (format.equals("12")) {
dateform = "hh:mmaa";
} else {
dateform = "HH:mm";
}
}else{
dateform = "HH:mm";
}
SimpleDateFormat sdf = new SimpleDateFormat(dateform);
String currenttime = sdf.format(now.getTime());
Log.e("MainActivity","currenttime:"+currenttime+"---format:"+format);
if(!TextUtils.isEmpty(format)) {
if (format.equals("12")) {
if (currenttime.contains("上午")) {
currenttime = "上午" + currenttime.substring(0, currenttime.indexOf("上午"));
} else {
currenttime = "下午" + currenttime.substring(0, currenttime.indexOf("下午"));
}
}
}
time_textview.setText(currenttime);
// mTimeZone.setSummary(ZoneGetter.getTimeZoneOffsetAndName(getActivity(),
// now.getTimeZone(), now.getTime()));
}
就这样就可以切换小时制了