How to get UTC offset in seconds in android

白昼怎懂夜的黑 提交于 2020-12-01 00:40:33

问题


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=Calendar.getInstance();
        TimeZone tz=c.getTimeZone();
        int offsetFromUtc=tz.getOffset(0)/1000;

When I put 0 in the tz.getOffset it means I just want the number of seconds from gmt. Let me know if what Im doing is correct. Thanks


回答1:


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.




回答2:


The default timezone of the emulator is GMT, meaning you will always get an offset of 0. Your code looks fine (I didn't try it). Try changing the timezone of your emulator to something else and check your code. Take a look in this open post: Link



来源:https://stackoverflow.com/questions/7289660/how-to-get-utc-offset-in-seconds-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!