Search code examples
javadayofweeklocaldatedate-manipulation

Java LocalDate How to utilize


input list

  1. from date ex) 2020-10-01
  2. to date ex) 2020-10-30
  3. List [day of week] ex) [sun,mon....]
  4. List [week] ex) [1,4,5]

I would like to know how to get a specific day of the week between the two dates. Thank.


Solution

  • java.time

    I too recommend that you use java.time, the modern Java date and time API, for your date work. My shot is:

        LocalDate fromDate = LocalDate.of(2020, Month.OCTOBER, 1);
        LocalDate toDate = LocalDate.of(2020, Month.OCTOBER, 30);
        List<DayOfWeek> daysOfWeek = List.of(DayOfWeek.SUNDAY, DayOfWeek.MONDAY);
        List<Integer> weeks = List.of(1, 4, 5);
        
        if (! YearMonth.from(fromDate).equals(YearMonth.from(toDate))) {
            throw new IllegalStateException("Covering more than one month is not yet supported");
        }
        
        WeekFields wf = WeekFields.SUNDAY_START;
        for (int week : weeks) {
            for (DayOfWeek dow : daysOfWeek) {
                LocalDate date = fromDate.with(wf.weekOfMonth(), week)
                        .with(wf.dayOfWeek(), dow.get(wf.dayOfWeek()));
                // Is date inside interval?
                if (! (date.isBefore(fromDate)  || date.isAfter(toDate))) {
                    System.out.println(date);
                }
            }
        }
    

    Output:

    2020-10-18
    2020-10-19
    2020-10-25
    2020-10-26
    

    The dates printed are Sunday and Monday of weeks 4 and 5 of October defining weeks in the American way where the week begins on Sunday (since you mentioned Sunday first in your example list) and week 1 is the week of October 1. Sunday and Monday of week 1 are not printed because they fall before October 1, that is, in September.

    Consider which week scheme you require. You may use for example WeekFields.ISO or WeekFields.of(Locale.getDefault()).

    I am finding the week first, then the day of week, because to me this is the natural way. I need to use the WeekFields object for both adjustments to make sure that the chosen week scheme is respected.

    If you need to cover more than one calendar month, iterate over the months and do the same for each. Also check that the result date falls within the month so duplicates near month borders are ignored.