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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With