开发者

GregorianCalendar shows odd values?

Ok.

calendar.get(Calendar.MONTH); 

returns the index of the current month. So for example if this line of code were to be executed right now, it'd return 7 for August.

However

calendar.get(Calendar.AUGUST); 

aswell a开发者_开发问答s

calendar.get(Calendar.MONTH); in april

returns 3?

This makes it rather hard for me to get the correct date values depending on my development context.

Can someone shed some light upon me why this is as is?


You shouldn't be using calendar.get(CALENDAR.AUGUST) - that's using a constant representing a value as if it were a constant representing a field type. It's unfortunate that the Calendar API is so poorly designed to let this happen, IMO, but you really need to understand why it's not meaningful.

A date in April returns 3 for the same reason that a date in August returns 7 - the months are 0-based in Calendar. I'm surprised that you were happy for August to return 7 but be confused by April returning 3...

Anyway, from the docs for Calendar.MONTH:

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

I would strongly advise you to look into Joda Time if you're doing anything even slightly non-trivial in Java with dates and times - it's a much saner and more expressive API than Date/Calendar.


Calendar.get() takes an integer with values such as 2 to request the Month or 7 to request the day of week. MONTH and DAY_OF_WEEK are final ints provided to let you specify those values more readably.

The final int AUGUST also happens to have a value 7, (same as DAY_OF_WEEK) but is not intended to be passed to get(), it's just a useful int corresponding to the value returned as the month in August (Java Months being zero based.)

Hence it is not meaningful to pass AUGUST to get(). This confusion is a relic of the pre-enum Java days. Had the Calendar class been designed to use enums it would all have been clearer.


This is completely unrelated to Android. java.util.Calendar has a bad interface for sure, but you are using it wrong too. calendar.get(Calendar.MONTH) returns the current month where January =0, calendar.get(Calendar.AUGUST) is meaningless. The const value for AUGUST happens to be 7 which is the same as Calendar.DAY_OF_WEEK, so you are effectively getting the day of week (TUESDAY). In short, don't do that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜