How to get UTC offset in seconds in android

后端 未结 2 1488
南笙
南笙 2021-02-07 02:23

I\'m trying to get the UTC offset in seconds in android. Since the emulator keeps returning 0, I can\'t tell if I\'m doing this correctly or not.

    Calendar c=         


        
2条回答
  •  醉梦人生
    2021-02-07 02:28

    Time Zone offsets can change during the year, perhaps the most common reason is Daylight Savings Time. Instead of passing 0 to TimeZone.getOffset() uses the current time to get the current offset, create a new Date and get its Time value:

    TimeZone tz = TimeZone.getDefault();
    Date now = new Date();
    int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
    

    The emulator defaults to UTC, try checking the available timezones to test. Also you can pass a timezone switch to set the timezone, check the documentation for -timezone.

提交回复
热议问题