Software internationalization
|
Friday Mar 28, 2008
Working with months in Java Calendar
Earlier I mentioned that many of the
The answer comes from the
Create a calendar using the
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 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 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) {
...
}
Posted at 09:29AM Mar 28, 2008 by John O'Conner in Java | Comments:
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||