tags:

views:

3597

answers:

7

How do you get Hours and Minutes since Date.getHours and Date.getMinutes got deprecated?

Note: The examples that I found in google search used the deprecated methods.

Thank you.

+2  A: 

See the java.util.Calendar implementations.

Malax
+10  A: 

From the Javadoc for Date.getHours

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

So use

Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);

and the equivalent for getMinutes.

Mark
+3  A: 

First, import java.util.Calendar

Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
James
+2  A: 

Try Calender. Use getInstance to get a Calender-Object. Then use setTime to set the required Date. Now you can use get(int field) with the appropriate constant like HOUR_OF_DAY or so to read the values you need.

http://java.sun.com/javase/6/docs/api/java/util/Calendar.html

Tobias Langner
A: 

I would recommend looking ad joda time. http://joda-time.sourceforge.net/

I was afraid of adding another library to my thick project, but it's just easy and fast and smart and awesome. Plus, it plays nice with existing code, to some extent.

alamar
+12  A: 

Try using Joda Time instead of standard java.util.Date classes. Joda Time library has much better API for handling dates.

DateTime dt = new DateTime();  // current time
int month = dt.getMonth();     // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day

See this question for pros and cons of using Joda Time library.

Joda Time may also be included to some future version of Java as a standard component, see JSR-310.


If you must use traditional java.util.Date and java.util.Calendar classes, see their JavaDoc's for help (java.util.Calendar and java.util.Date).

You can use the traditional classes like this to fetch fields from given Date instance.

Date date = new Date();   // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR);        // gets hour in 12h format
calendar.get(Calendar.MONTH);       // gets month number, NOTE this is zero based!
Juha Syrjälä
+1 for this. Farting about with java.util.Calendar is just not worth the grief, jodatime is so much more expressive.
skaffman
Pity JSR whatever is stalled...
Tom Hawtin - tackline
A: 

While I wouldn't recommend doing so, I think it's worth pointing out that although many methods on java.util.Date have been deprecated, they do still work. In trivial situations, it may be OK to use them. Also, java.util.Calendar is pretty slow, so getMonth and getYear on Date might be be usefully quicker.

skaffman