1

I'm working with an agenda in Java. I have stored in my database the day of the week, the start and end time of some labs availability.

Now I need to provide a service for a schedule system by showing only the unavailable times of the day. For example, if day one has start time 13:00 and end time 19:00, I need to return a range just like this: [00:00 - 13:00, 19:00 - 23:59] . Remembering that a day can have more than a range available.

Is there any Java Class or API that could help me on subtracting these ranges?

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
Andre
  • 431
  • 7
  • 23
  • Maybe this can help? https://stackoverflow.com/questions/4927856/how-to-calculate-time-difference-in-java – Nexevis May 02 '19 at 18:58
  • Yep, you can use [Duration or Period](https://docs.oracle.com/javase/tutorial/datetime/iso/period.html) – kolomiets May 02 '19 at 19:00

1 Answers1

1

My lib Time4J offers following solution for the subtraction problem:

ClockInterval fullDay = ClockInterval.between(PlainTime.of(0), PlainTime.of(24));
ClockInterval slot = ClockInterval.between(PlainTime.of(13, 0), PlainTime.of(19, 0));

IntervalCollection<PlainTime> icoll = IntervalCollection.onClockAxis().plus(fullDay);
List<ChronoInterval<PlainTime>> result = icoll.minus(slot).getIntervals();

The resulting list of half-open intervals (with open end) can be easily iterated through and gives the expected result {[T00:00/T13:00), [T19:00/T24:00)}. Every result interval can be converted to a standard ClockInterval, too. There are also various methods to print such intervals in a localized way. Furthermore, you might find the class DayPartitionBuilder interesting which allows to connect weekdays and time schedules in streaming, see the example given in the documentation.

About compatibility with java.time:

  • The between()-methods of ClockInterval also accept instances of java.time.LocalTime.
  • Every instance of PlainTime can be converted back to LocalTime by help of the method toTemporalAccessor() with the exception of the value 24:00 which exists in Time4J but not in java.time.LocalTime.
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • Hey bro, thanks for the tip. You did an amazing job with this lib, very powerful and very well designed. Really incredible, you are the man! I just solved my problem in few minutes... – Andre May 06 '19 at 21:00
  • 1
    @Andre Thank you. Your post makes me thinking about possible future enhancements, too, for example a constant for "full day" in `ClockInterval` and an extra minus()-method for simple cases as convenience. – Meno Hochschild May 07 '19 at 04:58