Reputation: 9691
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
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
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
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