Weeks between two dates

This example shows how to find the number of weeks between two dates using Java 8 date time api and Joda time. We will set the start date to January 1, 2005 and the end date to January 1, 2006. Then we will find the number of weeks between the start date and end date which equates to 52 weeks.

Java 8 Date and Time API

This snippet will find the difference between two dates in weeks using java 8 Duration.between and ChronoUnit.WEEKS.between. Both approaches will calculate the amount of time between two temporal objects in the form of weeks.

@Test
public void weeks_between_two_dates_in_java_with_java8 () {

    LocalDate startDate = LocalDate.of(2005, Month.JANUARY, 1);
    LocalDate endDate = LocalDate.of(2006, Month.JANUARY, 1);

    long weeksInYear = ChronoUnit.WEEKS.between(startDate, endDate);

    assertEquals(52, weeksInYear);
}

Joda Time

Using joda, this snippet will calculate number of weeks between two dates using Weeks.weeksBetween.

@Test
public void weeks_between_two_dates_in_java_with_joda () {

    DateTime start = new DateTime(2005, 1, 1, 0, 0, 0, 0);
    DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);

    Weeks weeks = Weeks.weeksBetween(start, end);

    int weeksInYear = weeks.getWeeks();

    assertEquals(52, weeksInYear);
}