Enzo95
Enzo95

Reputation: 23

Java - Define intervals of time with Joda

I have to model intervals of time that a commerce is open, for example: monday to friday 10hs-18hs, and with a function check if the commerce is open or not. I think the most rational is using the class "Interval" that Joda provides, but I can't instantiate an Interval only with days or hours. I must use Joda.

Upvotes: 1

Views: 233

Answers (1)

Andreas
Andreas

Reputation: 159096

Quoting javadoc of Interval:

A time interval represents a period of time between two instants.

Since "Monday at 10:00" is not an instant, you cannot use Interval.

The Joda-Time library doesn't have a class for what you want, so you'll have to write it yourself.

The requirement of "must use JODA" simple means that your class should take a LocalDateTime as input and use Joda-Time for querying the weekday and time-of-day.


A good reusable class (e.g. called OpenCalendar) might be used like this:

OpenCalendar openCal = new OpenCalendar();
openCal.add(DateTimeConstants.MONDAY   , new LocalTime(10, 0), new LocalTime(18, 0));
openCal.add(DateTimeConstants.TUESDAY  , new LocalTime(10, 0), new LocalTime(18, 0));
openCal.add(DateTimeConstants.WEDNESDAY, new LocalTime(10, 0), new LocalTime(18, 0));
openCal.add(DateTimeConstants.THURSDAY , new LocalTime(10, 0), new LocalTime(18, 0));
openCal.add(DateTimeConstants.FRIDAY   , new LocalTime(10, 0), new LocalTime(18, 0));

LocalDateTime now = LocalDateTime.now();
if (openCal.isOpen(now)) {
    // code here
}

Upvotes: 2

Related Questions