flyingfromchina
flyingfromchina

Reputation: 9691

How to create a calendar object in Java

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?

Upvotes: 0

Views: 48639

Answers (4)

Brian Agnew
Brian Agnew

Reputation: 272277

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.

Upvotes: 1

Tamas Mezei
Tamas Mezei

Reputation: 899

Something like this should work:

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

Upvotes: 1

João Silva
João Silva

Reputation: 91299

Use the setTime method:

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);

Upvotes: 23

Jim Garrison
Jim Garrison

Reputation: 86774

Calendar c = new GregorianCalendar();
c.setTime(date);

Upvotes: 1

Related Questions