2017年7月20日 星期四

How to check if system is 12 or 24 hour time format

Reference:

https://stackoverflow.com/questions/4392636/how-do-i-check-if-system-is-12-or-24-hour
https://stackoverflow.com/questions/23222199/12-24-hour-mode-conflict
https://stackoverflow.com/questions/8834452/androidchanging-time-format-as-per-the-devices-current-time-format

Code snippet:

private boolean mIs24HourFormat = false;
private TextView mTime;

MainActivity.java
@Overrideprotected void onCreate(Bundle savedInstanceState) {
    ......
    mIs24HourFormat = android.text.format.DateFormat.is24HourFormat(mContext);
    ....
    mTime.setText(getTime());
}

private String getTime() {
    DateFormat df =
null;
   
if(mIs24HourFormat){
        df =
new SimpleDateFormat(mContext.getResources().getString(R.string.time_format_24hr), Locale.getDefault());
    }
else{
        df =
new SimpleDateFormat(mContext.getResources().getString(R.string.time_format_12hr), Locale.getDefault());
    }
   
return df.format(Calendar.getInstance().getTime());
}


strings.xml
<string name="time_format_24hr" translatable="false">HH\uee01mm</string>
<
string name="time_format_12hr" translatable="false">h\uee01mm</string>



Note:

If you want to show the time format followed by system, you can use android widget TextClock.

沒有留言: