fork(2) download
  1. import java.time.DayOfWeek;
  2. import java.time.LocalDate;
  3. import java.time.format.DateTimeFormatter;
  4. import java.time.format.DateTimeParseException;
  5. import java.time.temporal.TemporalAdjusters;
  6. import java.util.Locale;
  7.  
  8. public class Main {
  9. public static void main(String[] args) {
  10. // Tests
  11. System.out.println("Count: " + countSundaysBetween("1900 1 1", "1902 1 1"));
  12. System.out.println();
  13. System.out.println("Count: " + countSundaysBetween("1000000000000 2 2", "1000000001000 3 2"));
  14. }
  15.  
  16. static int countSundaysBetween(String strStartDate, String strEndDate) {
  17. DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("uuuu M d", Locale.ENGLISH);
  18. DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.ENGLISH);
  19. int count = 0;
  20.  
  21. LocalDate start, end;
  22.  
  23. System.out.printf("Processing start date: %s and end date: %s%n", strStartDate, strEndDate);
  24.  
  25. try {
  26. start = LocalDate.parse(strStartDate, dtfInput);
  27. } catch (DateTimeParseException e) {
  28. System.out.printf("The start date %s can not be processed%n", strStartDate);
  29. return 0;
  30. }
  31.  
  32. try {
  33. end = LocalDate.parse(strEndDate, dtfInput);
  34. } catch (DateTimeParseException e) {
  35. System.out.printf("The end date %s can not be processed%n", strEndDate);
  36. return 0;
  37. }
  38.  
  39. for (LocalDate date = start.with(TemporalAdjusters.firstDayOfMonth()); !date.isAfter(end); date = date
  40. .plusMonths(1)) {
  41. if (date.getDayOfWeek() == DayOfWeek.SUNDAY) {
  42. System.out.println(date.format(dtfOutput));
  43. count++;
  44. }
  45. }
  46.  
  47. return count;
  48. }
  49. }
Success #stdin #stdout 0.21s 37276KB
stdin
Standard input is empty
stdout
Processing start date: 1900 1 1 and end date: 1902 1 1
1 April 1900
1 July 1900
1 September 1901
1 December 1901
Count: 4

Processing start date: 1000000000000 2 2 and end date: 1000000001000 3 2
The start date 1000000000000 2 2 can not be processed
Count: 0