fork download
  1. import java.time.DayOfWeek;
  2. import java.time.LocalDate;
  3. import java.time.YearMonth;
  4. import java.time.temporal.TemporalAdjusters;
  5. import java.util.List;
  6. import java.util.stream.Collectors;
  7.  
  8. public class Main {
  9. public static void main(String[] args) {
  10. // Test
  11. System.out.println(getWeekends(2));// All weekends of Feb in the current year
  12. System.out.println(getWeekends(2020, 2));// All weekends of Feb 2020
  13. }
  14.  
  15. /*
  16. * All weekends (Sat & Sun) of the given month in the current year
  17. */
  18. static List<LocalDate> getWeekends(int month) {
  19. LocalDate firstDateOfTheMonth = LocalDate.now().withMonth(month).with(TemporalAdjusters.firstDayOfMonth());
  20.  
  21. return firstDateOfTheMonth
  22. .datesUntil(firstDateOfTheMonth.plusMonths(1))
  23. .filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
  24. .collect(Collectors.toList());
  25. }
  26.  
  27. /*
  28. * All weekends (Sat & Sun) of the given year and the month
  29. */
  30. static List<LocalDate> getWeekends(int year, int month) {
  31. LocalDate firstDateOfTheMonth = YearMonth.of(year, month).atDay(1);
  32.  
  33. return firstDateOfTheMonth
  34. .datesUntil(firstDateOfTheMonth.plusMonths(1))
  35. .filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
  36. .collect(Collectors.toList());
  37. }
  38. }
Success #stdin #stdout 0.09s 52832KB
stdin
Standard input is empty
stdout
[2021-02-06, 2021-02-07, 2021-02-13, 2021-02-14, 2021-02-20, 2021-02-21, 2021-02-27, 2021-02-28]
[2020-02-01, 2020-02-02, 2020-02-08, 2020-02-09, 2020-02-15, 2020-02-16, 2020-02-22, 2020-02-23, 2020-02-29]