fork download
  1. import java.time.Duration;
  2. import java.time.LocalDate;
  3. import java.time.LocalTime;
  4. import java.time.ZoneId;
  5. import java.time.ZonedDateTime;
  6. import java.util.Objects;
  7.  
  8. class Main {
  9.  
  10. public static void main(String[] args) {
  11. var startDate = LocalDate.of(2021, 10, 7);
  12. var endDate = LocalDate.of(2021, 10, 14); // Exactly a week
  13. var zone = ZoneId.of("Europe/Amsterdam");
  14.  
  15. var result = startDate.datesUntil(endDate)
  16. .map(date -> nonWeekendHours(date, zone))
  17. .reduce(Duration.ZERO, Duration::plus);
  18. System.out.println(result);
  19. }
  20.  
  21. private static Duration nonWeekendHours(LocalDate date, ZoneId zone) {
  22. LocalTimeRange result;
  23. switch (date.getDayOfWeek()) {
  24. case MONDAY:
  25. case TUESDAY:
  26. case WEDNESDAY:
  27. case THURSDAY:
  28. result = new LocalTimeRange(LocalTime.MIN, null);
  29. break;
  30. case FRIDAY:
  31. result = new LocalTimeRange(null, LocalTime.NOON);
  32. break;
  33. case SATURDAY:
  34. case SUNDAY:
  35. result = new LocalTimeRange(null, null);
  36. break;
  37. default:
  38. throw new IllegalArgumentException("This cannot happen, actually");
  39. };
  40. return result.toDuration(date, zone);
  41. }
  42. }
  43.  
  44. class LocalTimeRange {
  45.  
  46. public static final LocalTimeRange EMPTY = new LocalTimeRange(null, null);
  47.  
  48. private final LocalTime start;
  49. private final LocalTime endExclusive;
  50.  
  51. public LocalTimeRange(LocalTime start, LocalTime endExclusive) {
  52. this.start = start;
  53. this.endExclusive = endExclusive;
  54. }
  55.  
  56. public Duration toDuration(LocalDate date, ZoneId zone) {
  57. if (start == null && endExclusive == null) {
  58. return Duration.ZERO;
  59. }
  60.  
  61. var s = ZonedDateTime.of(date, Objects.requireNonNullElse(start, LocalTime.MIN), zone);
  62. ZonedDateTime e;
  63. if (endExclusive != null) {
  64. e = ZonedDateTime.of(date, endExclusive, zone);
  65. }
  66. else {
  67. e = ZonedDateTime.of(date.plusDays(1), LocalTime.MIN, zone);
  68. }
  69. return Duration.between(s, e);
  70. }
  71. }
  72.  
Success #stdin #stdout 0.14s 56204KB
stdin
Standard input is empty
stdout
PT108H