问题描述
我正在尝试在android中获取以秒为单位的UTC偏移量.由于模拟器不断返回0,所以我无法确定自己是否正确执行了操作.
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;
当我在tz.getOffset中输入0时,这意味着我只想要距gmt的秒数.让我知道我在做什么是正确的.谢谢
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
推荐答案
时区偏移量在一年中可能会发生变化,也许最常见的原因是夏令时.而不是将0传递给 TimeZone.getOffset()使用当前时间获取当前偏移量,创建一个新的Date并获取其Time值:
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;
模拟器默认为UTC,请尝试检查可用的时区进行测试.您还可以通过时区开关来设置时区,查看文档-timezone.
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.
这篇关于如何在Android中以秒为单位获取UTC偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!