如何在安卓中获取时区偏移量?

5
3个回答

9

要获取当前与UTC的偏移量(以毫秒为单位,根据夏令时可能会有所变化):

return TimeZone.getDefault().getOffset(System.currentTimeMillis());

要获取RFC 822时区字符串,只需创建一个SimpleDateFormat实例即可:
return new SimpleDateFormat("Z").format(new Date());

格式为(+/-)HHMM。

0

所以,我尝试通过CalendarSimpleDateFormat获取GMT偏移量,但两者都返回0。我找到了使用Date类中弃用的方法解决的方案。所以,这段代码对我有效。

private double getOffset() {                                       
    Calendar calendar = Calendar.getInstance(Locale.ENGLISH);      
    int defHour = calendar.get(Calendar.HOUR_OF_DAY);              
    int defMinute = calendar.get(Calendar.MINUTE) + (defHour * 60);
    Date date = new Date(System.currentTimeMillis());              
    int curHour = date.getHours();                                 
    int curMinute = date.getMinutes() + (curHour * 60);            
    double offset = ((double) curMinute - defMinute) / 60;         
    return offset > 12? -24 + offset : offset;                     
}                                             

然后您可以格式化结果


0

这段代码返回给我GMT偏移量。

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);

它返回时区偏移量,例如:+0530


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接