Get all Fridays in a date Range in Java

后端 未结 7 673
梦如初夏
梦如初夏 2020-12-16 15:48

I recently came across a task where i have to get all Fridays in a date range. I wrote a small piece of code and was surprised see some strange behaviour.

Below is m

7条回答
  •  死守一世寂寞
    2020-12-16 16:10

    First off, I would not bother with weeks. Set the Calendar to the beginning of the range, and figure out which DOW it is, then increment to get to the next Friday, then simply loop adding 7 days until you are at the end of the range.

    Actually, since you are always only going forward, should be something like:

    int daysToAdd = FridayDOW - currentDOW;
    if (daysToAdd < 0) daysToAdd += 7; 
    Date startDate = currentDate.add(Calendar.DAYS, daysToAdd);
    

    Yeah, like that.

    Ok, actually, for kicks, here it is in Java 8:

    @Test
    public void canFindAllFridaysInRange(){
        start = LocalDate.of(2013, 5, 10);
        end = LocalDate.of(2013, 8,30);
    
        DayOfWeek dowOfStart = start.getDayOfWeek();
        int difference = DayOfWeek.FRIDAY.getValue() - dowOfStart.getValue();
        if (difference < 0) difference += 7;
    
        List fridaysInRange = new ArrayList();
    
        LocalDate currentFriday = start.plusDays(difference);
        do {
            fridaysInRange.add(currentFriday);
            currentFriday = currentFriday.plusDays(7);
        } while (currentFriday.isBefore(end));
    
        System.out.println("Fridays in range: " + fridaysInRange);
    }
    

    Got to love the new date classes!! Of course a lambda would condense this further.

提交回复
热议问题