tags:

views:

90

answers:

4

I need to turn a Date object into a calender in java, and try to access its field value for HOUR_OF_DAY. Does anybody know how to do it? Thanks

A: 
Calendar c = new GregorianCalendar();
c.setTime(date);
Jim Garrison
+11  A: 

Use the setTime method:

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
JG
... and then `int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);`
BalusC
Indeed, updated.
JG
+1  A: 

Something like this should work:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
Tamás Mezei
+1  A: 

Can I suggest using the Joda library if you're doing anything more than the most basic date/time work ?

DateTime dt = new DateTime();
int hour = dt.getHourOfDay();

I realise it's not quite what you're after, but the Joda date/time library offers the benefits of a much nicer and intuitive API, and avoids the non-intuitive gotchas of non-thread-safe date/time formatters It's well worth checking out.

Brian Agnew
Yes, and it will still be _the_ date/time library in the near future, as it doesn't look like JSR-310 (https://jsr-310.dev.java.net/) is going to be ready for Java 7.
JG