Get all Fridays in a date Range in Java

后端 未结 7 668
梦如初夏
梦如初夏 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:04

    Here a solution based on new stream-features of Java-8 and using my library Time4J (v4.18 or later):

    String start = "01/01/2009";
    String end = "12/09/2013";
    
    ChronoFormatter f =
        ChronoFormatter.ofDatePattern("dd/MM/yyyy", PatternType.CLDR, Locale.ROOT);
    
    PlainDate startDate =
        f.parse(start).with(PlainDate.DAY_OF_WEEK.setToNextOrSame(Weekday.FRIDAY));
    PlainDate endDate = f.parse(end);
    
    Stream fridays =
        DateInterval.stream(Duration.of(1, CalendarUnit.WEEKS), startDate, endDate);
    
    fridays.forEachOrdered(System.out::println);
    
    // output
    2009-01-02 
    2009-01-09 
    ... 
    2013-08-30 
    2013-09-06
    
    // other example: list of fridays in ISO-8601-format
    List result =
      DateInterval.between(startDate, endDate)
        .stream(Duration.of(1, CalendarUnit.WEEKS))
        .map((date) -> date.toString()) // or maybe use dd/MM/yyyy => f.format(date)
        .collect(Collectors.toList());
    

    By the way, Java-9 will offer a similar solution (but with exclusive end date boundary), see also this enhancement-issue.

提交回复
热议问题