Reputation: 19562
If I have a timezone e.g. “GMT-05:00”
How can I find how many hours is the difference with my current location using Joda?
I am using this code:
TimeZone tz = TimeZone.getTimeZone("GMT" + gmtTZ);
int offset = tz.getOffset((new DateTime().getMillis()));
System.out.println(“— > “+offset / 3600000d);
Gives me -5, but it does not take into account the time difference of my timezone.
Upvotes: 1
Views: 97
Reputation: 2485
Read the documentation of getOffset
method. Millis from date does not contain any information about timezone and getOffset
takes millis parameter in order to tell if this particular date is within daylight saving time. And if it is you will get one hour more. The way you are doing it you will never get a difference, your result can only be -5/-4 hours.
You do not even need JodaTime:
TimeZone timezone = TimeZone.getTimeZone("GMT-5");
TimeZone localTimeZone = TimeZone.getDefault();
int timeZoneOffset = timezone.getOffset(System.currentTimeMillis());
int localTimeZoneOffset = localTimeZone.getOffset(System.currentTimeMillis());
int difference = Math.abs(timeZoneOffset - localTimeZoneOffset ) / 3600000;
If you want JodaTime just replace System.currentTimeMillis()
with DateTime.now().getMillis()
but I do not see the point other than testability.
Upvotes: 1