Week between two dates Java + Joda Time

血红的双手。 提交于 2019-12-05 13:59:46

JodaTime Weeks.weeksBetween(s, e) returns only whole week count. Incomplete weeks are not counted. To resolve this, you must garantee that the days are at the start and at the end of the week. Try this:

int weeks = Weeks.weeksBetween(s.dayOfWeek().withMinimumValue().minusDays(1), 
            e.dayOfWeek().withMaximumValue().plusDays(1)).getWeeks();

The minusDays/plusDays will garantee that the weeks i'm trying to count are full.

Same logic apply for Months:

int months = Months.monthsBetween(s.dayOfMonth().withMinimumValue().minusDays(1),
             e.dayOfMonth().withMaximumValue().plusDays(1)).getMonths();
    int OFFSET_ONE = 1;

    DateTime t1 = new DateTime().withDate(2012, 02, 29).withDayOfWeek(1);
    DateTime t2 = new DateTime().withDate(2012, 03, 05).withDayOfWeek(7);

    int week1 = t2.weekOfWeekyear().get(); 
    int week2 = t1.weekOfWeekyear().get();

    System.out.println(week1-week2+OFFSET_ONE); // add OFFSET_ONE

does it give what you are after?

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