简体   繁体   English

如何知道TimeZone与UTC的区别?

[英]How to know TimeZone difference to UTC?

I want to know how I can recuperate GMT +1 from java.util.TimeZone . 我想知道如何从java.util.TimeZone恢复GMT +1 For example I have TimeZone.getTimeZone("Europe/Madrid") and I want to know that value is GMT +1 or TimeZone.getTimeZone("Atlantic/Canary") is GMT . 例如,我有TimeZone.getTimeZone("Europe/Madrid") ,我想知道值是GMT +1TimeZone.getTimeZone("Atlantic/Canary")GMT

As the question has been already answered , but still a friendly suggestion use Joda Date Time API , it is very powerful and covers all the limitation that was there in JDK Date and Time classes. 由于问题已经得到解答,但仍使用Joda Date Time API进行友好建议,它非常强大,并且涵盖了JDK Date和Time类中存在的所有限制。

Cheers 干杯

You can use getOffset method. 您可以使用getOffset方法。 This method requires a long date as it takes account of daylight savings etc. 此方法需要long date因为它考虑了夏时制等。

public static void main(String[] args) throws Exception {
    final TimeZone madrid = TimeZone.getTimeZone("Europe/Madrid");
    final TimeZone canaries = TimeZone.getTimeZone("Atlantic/Canary");
    final long now = System.currentTimeMillis();

    System.out.println(madrid.getOffset(now));
    System.out.println(canaries.getOffset(now));
}

As you can see this returns the offset in millis 如您所见,这将返回以毫秒为单位的偏移量

7200000
3600000

You can then use TimeUnit to convert to hours: 然后,您可以使用TimeUnit转换为小时:

System.out.println(TimeUnit.MILLISECONDS.toHours(madrid.getOffset(now)));
System.out.println(TimeUnit.MILLISECONDS.toHours(canaries.getOffset(now)));

Output: 输出:

2
1

The getOffset method returns the difference in milliseconds. getOffset方法返回以毫秒为单位的差异。

Note that these time zones also use DST, their current offset from UTC is 2 and 1 hours respectively. 请注意,这些时区也使用DST,它们与UTC的当前偏移分别为2小时和1小时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM