0

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

4 Answers 4

23

Use the setTime method:

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
Sign up to request clarification or add additional context in comments.

1 Comment

... and then int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
1
Calendar c = new GregorianCalendar();
c.setTime(date);

Comments

1

Something like this should work:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.HOUR_OF_DAY));

Comments

1

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.