Retrieving Date Elements
Posted by joconner on March 12, 2007 at 2:48 AM EDT
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
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 >>
Blog Links >>
- Login or register to post comments
- Printer-friendly version
- joconner's blog
- 1113 reads





