Java GregorianCalendar and Calendar misplace weekends, days in a month for August and September, 2010

Deadly 提交于 2019-12-02 08:55:33

I strongly suspect you're not taking into account the fact that the month is 0-based. So this:

startDate.set(2010, 8, 28);

is setting it to September 28th 2010. You haven't said what you expect it to be, but I suspect you wanted August (which is month 7 in java.util.Calendar).

I suspect this is the problem, given that October 2nd and 3rd are Saturday and Sunday.

Can I strongly recommend that you use Joda Time as your date and time API instead of java.util.{Date,Calendar}? The built-in classes have lots of gotchas like this.

If you want to continue to use java.util.Calendar, you should probably also use the Calendar.JANUARY, Calendar.FEBRUARY, etc. constants.

As others have already mentioned it might be some of the common "off by one" errors this library design helps to make. The Java API is more or less some wrapping of a UNIX timestamp largely inspired by some C library.

You should at least use the appropriate Enumerations to improve readability and make sure to not pass Date/Calendar objects to other methods which could work with some immutable representation (String, Long, ...) of the data depending on the use case.

If you are heavily involved with Times, Dates and Calendars you should consider using JodaTime and look into JSR 310, the Date and Time API which might appear in a future Java release.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!