Reputation: 13872
Why does below line print false? i think it should print true.
TimeZone.getTimeZone("UTC+5:30").hasSameRules(TimeZone.getTimeZone("GMT+5:30")
Upvotes: 8
Views: 761
Reputation: 86280
Since you are located in India, you should use
ZoneId india = ZoneId.of("Asia/Kolkata");
Two messages:
TimeZone
class has design problems and is long outdated. The same goes for its friends like Calender
and SimpleDateFormat
. So don’t use them. Instead use java.time, the modern Java date and time API. Its replacement for TimeZone
is the ZoneId
class (and ZoneOffset
for an offset from UTC, but don’t use that as a time zone, it isn’t one, see the next item).Asia/Kolkata
clearly conveys. Also Asia/Kolkata
is future-proof in case at some point in time the politicians change the UTC offset for India or introduce summer time (DST). While this is unlikely for India, it happens all the time in other places in the world, so It’s better to make it a habit to use the region/city format always.For just one of the many design advantages of the modern API it rejects the invalid formats that you used. Try the modern version of your code:
ZoneId.of("UTC+5:30").getRules().equals(ZoneId.of("GMT+5:30").getRules()) // invalid formats
This throws: java.time.DateTimeException: Invalid ID for offset-based ZoneId: UTC+5:30
. Now you know from the outset what’s wrong: UTC+5:30
is not a valid time zone ID.
Link: Oracle tutorial: Date Time explaining how to use java.time
.
Upvotes: 3
Reputation: 21435
The answer is in the JavaDoc of TimeZone#getTimeZone:
the ID for a TimeZone, either an abbreviation such as "PST", a full name such as "America/Los_Angeles", or a custom ID such as "GMT-8:00"
Returns: the specified TimeZone, or the GMT zone if the given ID cannot be understood.
And (from the class documentation)
[...] The syntax of a custom time zone ID is:
CustomID:
GMT Sign Hours : Minutes
GMT Sign Hours Minutes
GMT Sign Hours
The ID "UTC+5:30"
is not a valid TimeZone ID (as per the specification of the method/class) and is interpreted as "GMT" zone, which is clearly distinct from the "GMT+5:30" zone.
Upvotes: 8