Joda-Time: Get max number of weeks for particular year

前端 未结 3 1709
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 17:31

How do I get the maximum number of weeks for a particular year with Joda-Time?

3条回答
  •  旧巷少年郎
    2021-02-15 18:25

    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.

提交回复
热议问题