Skip to main content

Retrieving Date Elements

Posted by joconner on March 11, 2007 at 11:48 PM PDT

Earlier I mentioned that many of the Date constructors and methods are deprecated. You shouldn't use them. Someone immediately wondered how they were supposed to find out what the date actually meant...what year is it? month? day? If you can't ask the date object directly, what should you do?

The answer comes from the java.util.Calendar class. Use a Calendar to create a specific date from year, month, day, and time values. Use that same calendar to extract specific date-time values from a date object.

Create a calendar using the Calendar factory method getInstance. The method is overloaded so that you can create a calendar for

  • the default locale and timezone
  • a specific locale for the default timezone
  • a specific timezone for the default locale
  • a specific timezone and specific locale

The timezone helps the calendar to set its initial time correctly using the appropriate time offsets from GMT. The locale information helps the calendar to know what type of calendar to create. The vast majority of locales support a Gregorian calendar, but the Java platform also supports Thai and Japanese calendars.

In order to get specific time elements from a date, you have to use a Calendar. Once you have a calendar, set it to a specific date like this:

Calendar cal = Calendar.getInstance();
cal.setTime(aDate);

Calendar has a get method that lets you retrieve the individual time elements of its set date. Use static constants to extract elements:

int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR);
int hour24 = cal.getCalendar.HOUR_OF_DAY);
int min= cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int ms = cal.get(Calendar.MILLISECOND);

So, there you have it. Use the static final constants of the Calendar class with the get method instead of the deprecated methods of Date itself.

I have heard some people complain that month values are 0-based, but day of month values are 1-based. I think the complaint is based on the inconsistency. OK, I see your point. To help resolve some of the confusion using 0 based months, use the predefined Calendar constants instead of hard-coded numbers. It's not such a big problem after all.

The following code shows what I mean:

if (month == 1) { // maybe you meant JANUARY... or do you really mean FEBRUARY?
  ...
}

if (month == Calendar.JANUARY) { // avoid the problem by using Calendar constants
   ...
} else if (month == Calendar.FEBRUARY) {
   ...
}
Related Topics >>