Android how to set time zone through application

前端 未结 3 850
孤城傲影
孤城傲影 2021-01-12 10:17

Android provides a permission called \"SET_TIME_ZONE\" with OS permission level \"dangerous\". Does anyone know that given an application with this permission, how can the a

相关标签:
3条回答
  • 2021-01-12 10:37

    If your objective is to change the system's default time zone, then use setTimeZone() of AlarmManager.

    0 讨论(0)
  • 2021-01-12 10:38

    You can set the TimeZone in multiple ways:

    1. You can use TimeZone.setDefault() which will change the TimeZone for the current process only. But as noted in the docs, this is not garanteed to last for the whole application lifecycle.

    2. You can use setTimeZone() of AlarmManager to change the TimeZone of the whole device. But you need the "SET_TIME_ZONE"-permission for that.

    If you think 1. is to dangerous and you don't have the permission for 2. your best approach is to get every Date from Calendar and set the TimeZone on your Calendar-instance via setTimeZone().

    0 讨论(0)
  • 2021-01-12 10:45

    For Setting of the Time Zone Programetically you need to use the Date Class. See its Reference Documents here.

    You need to use the setTimeZone() method of SimpleDateFormat Class.

    Following is sample code for settings Time Zone of according to America

    // First Create Object of Calendar Class
    Calendar calendar = Calendar.getInstance();        
    // Now Set the Date using DateFormat Class
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss z"); 
    // Finally Set the time zone using SimpleDateFormat Class's setTimeZone() Method
    sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); 
    
    0 讨论(0)
提交回复
热议问题