Android时间时区设置和获取

    xiaoxiao2021-12-14  19

    判断系统是否自动获取时区

    public static boolean isTimeZoneAuto(Context mContext) { try { return android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.AUTO_TIME_ZONE) > 0; } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); return false; } }

    设置自动获取时区

    public static void setAutoTimeZone(Context mContext, int checked) { android.provider.Settings.Global.putInt(mContext.getContentResolver(), android.provider.Settings.Global.AUTO_TIME_ZONE, checked); }

    获取系统默认时区

    public static String getTimeZone() { return TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT); }

    设置系统默认时区

    // 需要添加权限<uses-permission android:name="android.permission.SET_TIME_ZONE" /> public static void setChinaTimeZone(Context context) { /* TimeZone.getTimeZone("GMT+8"); TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));*/ AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmManager.setTimeZone("Asia/Shanghai");// Asia/Taipei//GMT+08:00 }

    判断系统是否自动获取日期和时间

    try { return android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.AUTO_TIME) > 0; } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); return false; } }

    设置系统自动获取日期和时间

    public static void setAutoDateTime(Context mContext, int checked) { android.provider.Settings.Global.putInt(mContext.getContentResolver(), android.provider.Settings.Global.AUTO_TIME, checked); }

    获取系统当前时间

    public static String currentTime() { long currentTime = System.currentTimeMillis(); Date date = new Date(currentTime); SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); return formatter.format(date); }

    设置系统当前时间

    // 需要系统权限 public static boolean setSytemTime(long value){ long settingTime = value; if (value/1000 < Integer.MAX_VALUE){ SystemClock.setCurrentTimeMillis(settingTime); } }

    判断系统是否是24h格式(12h同理)

    public static boolean is24Hour(Context mContext) { ContentResolver cv = mContext.getContentResolver(); String strTimeFormat = android.provider.Settings.System.getString(cv, android.provider.Settings.System.TIME_12_24); if (strTimeFormat != null && strTimeFormat.equals("24")) { return true; } return false; }

    设置系统为24h格式(12h同理)

    public static void set24Hour(Context mContext) { ContentResolver cv = mContext.getContentResolver(); android.provider.Settings.System.putString(cv, Settings.System.TIME_12_24, "24"); }

    说明:系统时区和时间是否自动获取是作为参数存储到数据库的,所以只需要修改参数即选中是否同步时间 参考:http://www.jianshu.com/p/6c6a6091545d

    转载请注明原文地址: https://ju.6miu.com/read-963347.html

    最新回复(0)