Joda-Time: Get max number of weeks for particular year
new DateTime().withYear(PARTICULAR_YEAR).weekOfWeekyear().getMaximumValue();
@cody Comment
Difference between the two methods
.withWeekOfWeekyear()
and.withWeekyear()
Example
new DateTime().withDate(2011, 1, 2);
2/1/2011 : Sunday, last day of last week of 2010 (27/12/2010 - 2/1/2011)
dayOfWeek : 7
weekOfWeekyear : 52
weekyear : 2010
new DateTime().withDate(2011, 1, 3);
3/1/2011 : Monday, first day of first week of 2011 (3/1/2011 - 9/1/2011)
dayOfWeek : 1
weekOfWeekyear : 1
weekyear : 2011
I know that replying to a question this old is a necromancy but the accepted answer (by lschin) has a bug - while most of the time it will return correct value, it will sometimes return a wrong one, depending on when the calculation was performed. For example:
new DateTime().withYear(2014).weekOfWeekyear().getMaximumValue();
If you run the above on 28 Dec 2014, you'll get the correct value of 52.
However, the same code when run just a day later, on 29 Dec 2014, will return the value of 53. Which is obviously a problem because a given year has a constant number of weeks (not to mention the fact that you wouldn't want your methods work only some of the time). You can test this by changing your system date or by using a fixed date instead of new Date()
.
The problem here is weekOfWeekyear()
which can increment the given year value if new DateTime()
happens to return a near end-of-year date. This is not a problem when the current and the next year both have the same amount of weeks but will be a problem otherwise. So, to correct this, use:
new DateTime().withWeekyear(2014).weekOfWeekyear().getMaximumValue();
^^^^
This will make sure you won't change increment a year on those rare occasions and get consistently correct results.