Get TimeZone offset value from TimeZone without TimeZone name

后端 未结 7 840
[愿得一人]
[愿得一人] 2020-12-02 10:22

I need to save the phone\'s timezone in the format [+/-]hh:mm

I am using TimeZone class to deal with this, but the only format I can get is the following:

         


        
7条回答
  •  庸人自扰
    2020-12-02 11:03

    @MrBean - I was in a similar situation where I had to call a 3rd-party web service and pass in the Android device's current timezone offset in the format +/-hh:mm. Here is my solution:

    public static String getCurrentTimezoneOffset() {
    
        TimeZone tz = TimeZone.getDefault();  
        Calendar cal = GregorianCalendar.getInstance(tz);
        int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
    
        String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
        offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
    
        return offset;
    } 
    

提交回复
热议问题