Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I use instead of the deprecated Date.getHours()

If a method is deprecated in Java there will be a another better way to have same functionality, right?

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

As getHours() is deprecated, what is the best way to get hours using only the Date class?

like image 336
sunleo Avatar asked Jan 23 '13 17:01

sunleo


3 Answers

As others already stated Javadoc suggests to instead use Calendar.get(Calendar.HOUR_OF_DAY).

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

Here's how you could do it for already set Date:

int getHourOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(Calendar.HOUR_OF_DAY);
}

Use Calendar.HOUR_OF_DAY if you want number from 0-23 and Calendar.HOUR for 0-11.

like image 151
beam022 Avatar answered Oct 16 '22 09:10

beam022


Javadoc explicitly suggests

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

Joda library is another best alternative to handle Date and Time.

like image 31
kosa Avatar answered Oct 16 '22 09:10

kosa


These methods are indeed deprecated.

You should now use java.util.Calendar#get()

So your example becomes

Calendar cal = Calendar.getInstance();
cal.get(Calendar.HOUR);

see the javadoc of this class.

Note that you can get a Date object by calling getTime on cal.

like image 10
autra Avatar answered Oct 16 '22 11:10

autra