简体   繁体   中英

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?

Use the setTime method:

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

Something like this should work:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM