简体   繁体   中英

How do I get specific date information using a Calendar object in Java?

I'm currently trying to use a Calendar object in order to get information about the current date. Specifically, I need to know the day of the week, time (h/m/s), and AM/PM. I originally intended to use a Date object, but answers on other questions suggested that using Calendar would be better. However, from looking at the API, I'm unsure about how to get the individual pieces from the Calendar object.

However, from looking at the API, I'm unsure about how to get the individual pieces from the Calendar object.

You use get with the relevant field, eg:

int months = yourCalendar.get(Calendar.MONTH);

Having said that, I see people recommend Joda Time here on SO a lot , so if you're not tied to Calendar (and from your question it sounds as though you aren't), that may be worth a look. (I certainly plan to look at it the next time I'm doing date stuff in Java.)

http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html

What's not clear about it? It's filled with examples. Here are a few of those you named:

System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

Use Joda Time. Much easier to work with this type of information.

DateTime dateTime = new DateTime();
System.out.println("Day of week is " + dateTime.getDayOfWeek());
System.out.println("Hour is " + dateTime.getHourOfDay());

etc.

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