简体   繁体   中英

“Code deprecation ” in java

I use the date class to get the current hour with the function

Date date = new Date();
int t=date.getHours();

and eclipse keeps complaining about code deprecation. Everything works absolutely fine, but it keeps warning me about it, is there a reason I should change it? is there an alternative to getting current time?

If you look at the java.util.Date API

getHours() is a deprecated method

Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY).

Some parts of a library are marked deprecated when an issue is found with them but the designers decide that an improvement on the existing part could break many existing programs that already rely on the old behavior.

So, they keep the existing part, at least for some time (to maintain the ability of existing sources to compile until they are updated), while usually offering an alternative instead.

Now, regarding time in Java, most people recommend Joda time .

The reason why you should change it is that java.util.Date is broken in many subtle ways. Your code may work in certain situations and fail in others (for example, when you run it on a computer with a different time zone, when a cracker attacks your application, when someone messed with serialized Date objects, ...)

In 2013, you shouldn't use java.util.Date anymore. Use Calendar , if you must, or the much better joda-time library .

Date#getHours is deprecated:

As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY).

The reason to change is that deprecated code is "marked" to be removed in future release, so you should not use deprecated method in your code if you plan to maintain it over time.
As for what to do to get the hour, from Date Javadoc:

As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY).

Date.getHours is deprecated as of JDK version 1.1. You should use java.util.Calendar.get(Calendar.HOUR_OF_DAY) instead:

Calendar c = Calendar.getInstance();
int t = c.get(Calendar.HOUR_OF_DAY);

http://uk.answers.yahoo.com/question/index?qid=20081123050802AAL0gAm

Basically, you can still use the method. But it may not be supported for the next few versions of java.

BTW, you can get around the problem by using Calendar class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM