Why was Date.getTimezoneOffset deprecated?

时光怂恿深爱的人放手 提交于 2019-12-23 07:35:24

问题


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.


回答1:


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.




回答2:


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.




回答3:


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).



来源:https://stackoverflow.com/questions/10486064/why-was-date-gettimezoneoffset-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!