21

I want to get the current hour,minute, and second from the Date object.

This is my code:

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

But I get a kind of error, the getHours() part doesnt work. I get a "The method getHours() from the type Data is deprecated". What does that mean, and how do I get the hour,minutes, and seconds?

CJR
  • 3,174
  • 6
  • 34
  • 78
  • 1
    Deprecation is not an error, but a warning. While it isn't good practice to use a deprecated method, it still "should work", though bugs for it won't be fixed by the author, and it might disappear later. – nanofarad Aug 24 '14 at 16:54
  • 1
    Have a look at http://stackoverflow.com/a/14938297/1848261 – Jayanth Aug 24 '14 at 16:54
  • 1
    this is superseeded by java8: https://stackoverflow.com/questions/25539891/how-to-get-the-current-hour-with-new-date-time-api-in-java-8 – Alexander Oh Nov 14 '17 at 11:18

1 Answers1

51

Use Calendar:

Calendar cal = Calendar.getInstance();
cal.setTime(date);  
int hours = cal.get(Calendar.HOUR_OF_DAY);

From Date javadoc:

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

Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone. The value returned is between 0 and 59.

Community
  • 1
  • 1
nanofarad
  • 40,330
  • 4
  • 86
  • 117