Mathew Rock
Mathew Rock

Reputation: 989

How to know TimeZone difference to UTC?

I want to know how I can recuperate GMT +1 from java.util.TimeZone. 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.

Upvotes: 1

Views: 179

Answers (3)

saurav
saurav

Reputation: 3462

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.

Cheers

Upvotes: 3

Joni
Joni

Reputation: 111219

The getOffset method returns the difference in milliseconds.

Note that these time zones also use DST, their current offset from UTC is 2 and 1 hours respectively.

Upvotes: 1

Boris the Spider
Boris the Spider

Reputation: 61128

You can use getOffset method. This method requires a long date as it takes account of daylight savings etc.

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:

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

Output:

2
1

Upvotes: 2

Related Questions