Get TimeZone offset value from TimeZone without TimeZone name

后端 未结 7 819
[愿得一人]
[愿得一人] 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 10:56

    We can easily get the millisecond offset of a TimeZone with only a TimeZone instance and System.currentTimeMillis(). Then we can convert from milliseconds to any time unit of choice using the TimeUnit class.

    Like so:

    public static int getOffsetHours(TimeZone timeZone) {
        return (int) TimeUnit.MILLISECONDS.toHours(timeZone.getOffset(System.currentTimeMillis()));
    }
    

    Or if you prefer the new Java 8 time API

    public static ZoneOffset getOffset(TimeZone timeZone) { //for using ZoneOffsett class
        ZoneId zi = timeZone.toZoneId();
        ZoneRules zr = zi.getRules();
        return zr.getOffset(LocalDateTime.now());
    }
    
    public static int getOffsetHours(TimeZone timeZone) { //just hour offset
        ZoneOffset zo = getOffset(timeZone);
        TimeUnit.SECONDS.toHours(zo.getTotalSeconds());
    }
    

提交回复
热议问题