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.ArrayList;
  6. import java.util.List;
  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. List<LocalDate> list = new ArrayList<>();
  21.  
  22. for (LocalDate date = firstDateOfTheMonth; !date
  23. .isAfter(firstDateOfTheMonth.with(TemporalAdjusters.lastDayOfMonth())); date = date.plusDays(1))
  24. if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
  25. list.add(date);
  26.  
  27. return list;
  28. }
  29.  
  30. /*
  31. * All weekends (Sat & Sun) of the given year and the month
  32. */
  33. static List<LocalDate> getWeekends(int year, int month) {
  34. LocalDate firstDateOfTheMonth = YearMonth.of(year, month).atDay(1);
  35. List<LocalDate> list = new ArrayList<>();
  36.  
  37. for (LocalDate date = firstDateOfTheMonth; !date
  38. .isAfter(firstDateOfTheMonth.with(TemporalAdjusters.lastDayOfMonth())); date = date.plusDays(1))
  39. if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
  40. list.add(date);
  41.  
  42. return list;
  43. }
  44. }
Success #stdin #stdout 0.1s 49392KB
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]