fvgs
fvgs

Reputation: 21982

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.

Upvotes: 0

Views: 924

Answers (2)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

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()));

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075587

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, e.g.:

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.)

Upvotes: 3

Related Questions