Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was Date.getTimezoneOffset deprecated?

The documentation for Date.getTimezoneOffset says:

Deprecated. As of JDK version 1.1, replaced by -(Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000).

Why was it deprecated? Is there a shorter way (Apache Commons?) to get the offset from UTC in hours/minutes? I have a Date object ... should I convert it to JodaDate for this?

And before you ask why I want the UTC offset - it's just to log it, nothing more.

like image 229
ripper234 Avatar asked May 07 '12 17:05

ripper234


3 Answers

There are 2 questions here.

  1. Why was Date.getTimezoneOffset deprecated?

I think it is because they actually deprecated nearly all methods of Date and moved their logic to calendar. We are expected to use generic set and get with the parameter that says which specific field we need. This approach has some advantages: less number of methods and the ability to run setters in a loop passing a different field each time. I personally used this technique a lot: it makes code shorter and easier to maintain.

  1. Shortcut? But what's wrong with call

Calendar.get(Calendar.DST_OFFSET) comparing to Calendar.getTimeZoneOffset()

As far as I can see the difference is 6 characters.

Joda is a very strong library and if you really have to write a lot of sophisticated date manipulation code switch to it. I personally use the standard java.util.Calendar and don't see any reason to use external libraries: good old calendar is good enough for me.

like image 155
AlexR Avatar answered Nov 15 '22 16:11

AlexR


All of the date manipulation logic was moved out of Date once the Java implementers realized that it might need to be implemented differently for different types of calendars (hence the need to use a GregorianCalendar to retrieve this info now). A Date is now just a wrapper around a UTC time value.

like image 38
jtahlborn Avatar answered Nov 15 '22 15:11

jtahlborn


Take care before you paste code from this page. Perhaps just me but I believe that in order to get the tz offset in minutes you need to do

int tzOffsetMin = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET))/(1000*60);

rather than what the Javadoc says, which is:

int tzOffsetMin = -(cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET))/(1000*60);



Calendar.ZONE_OFFSET gives you the standard offset (in msecs) from UTC. This doesn't change with DST. For example for US East Coast timezone this field will always be -6 hours regardless of DST.

Calendar.DST_OFFSET gives you the current DST offset (in msecs) - if any. For example during summer in a country that uses DST this field is likely to have the value +1 hour (1000*60*60 msecs).

like image 38
peterh Avatar answered Nov 15 '22 15:11

peterh