您的位置:首页 > 移动开发 > Android开发

Android时间时区设置和获取

2016-12-02 12:01 344 查看

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

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android
相关文章推荐