javadateweek-number

Week numbers from start date to end date Java


I trying to get the week numbers which fall between a given start date and end date in Java. This is ISO8601 date.

Example 
startDate - "2018-08-24T12:18:06,166"
endDate -  "2019-08-24T11:18:06,166"

The current week number is 34.

For this example, I would get 34,35,36... Last week number of 2018..1,2...last week number of 2019 and so on

Is there a good solution to this ?

Presently I got it worked with same year date range, what I tried is, I get the start week number and end week number from the start date and end date, and then I loop it giving the start value and end value. But if the date range falls in multiple years, how would it be? Can any one help me


Solution

  • If you are using Java 8 you can use java.time API Like so :

    int addWeek = 0;
    if(startDate.get(WeekFields.ISO.weekOfYear()) < endDate.get(WeekFields.ISO.weekOfYear())){
        addWeek = 1;
    }
    long weeks = WEEKS.between(startDate, endDate) + addWeek;//Get the number of weeks in your case (52)
    List<Integer> numberWeeks = new ArrayList<>();
    if (weeks >= 0) {
        int week = 0;
        do {
            //Get the number of week
            int weekNumber = startDate.plusWeeks(week).get(WeekFields.ISO.weekOfYear());
            numberWeeks.add(weekNumber);
            week++;
        } while (week <= weeks);
    }
    

    Ideone demo

    [34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 
     22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]
    

    Note that you get both week numbers from both years, weeks of 2018 [34-52], then weeks of 2019 [1-33]