Search code examples
javajsondatetime-comparisontimeofday

Compare Date and Time range with Java


I have this input:

{
  "MONDAY" : "02:39:00"
}

Which is a DAY and time that needs to compared to

  "availability" : {
    "SUNDAY" : {
      "from" : "00:00",
      "to" : "10:00"
    },
    "MONDAY" : {
      "from" : "00:00",
      "to" : "10:00"
    }
  }

What's the best way to compare if the availability in fact contains a DAY in which the time in the query 02:39:00 is within.

As such, it can be represented in Java-form:

boolean isOpen = checkIfOpen("MONDAY", "02:39:00", availabilityJSONObject);

And which in this case, the value of isOpen would be true.


Solution

  • As Pranav balu already said, use Java objects/data structures for your data. Use a JSON library like Jackson or Gson for converting your JSON input to Java types. You will need a Java type for the daily availability range. For example:

    public class AvailabilityRange {
    
        LocalTime opens;
        LocalTime closes;
        
        public AvailabilityRange(String from, String to) {
            opens = LocalTime.parse(from);
            closes = LocalTime.parse(to);
        }
        
        public boolean inRange(String timeString) {
            LocalTime time = LocalTime.parse(timeString);
            return (! time.isBefore(opens)) && time.isBefore(closes);
        }
    }
    

    I have provided a convenience constructor and a convenience method that accept String arguments. You may want a constructor and a method that accept LocalTime, or both.

    Example use:

            Map<DayOfWeek, AvailabilityRange> availability
                    = new EnumMap<DayOfWeek, AvailabilityRange>(
                            Map.of(DayOfWeek.SUNDAY, new AvailabilityRange("00:00", "10:00"), 
                                    DayOfWeek.MONDAY, new AvailabilityRange("00:00", "10:00")));
            
            String dayString = "MONDAY";
            String timeString = "02:39:00";
            
            boolean isOpen;
            AvailabilityRange availabilityForDay
                    = availability.get(DayOfWeek.valueOf(dayString));
            if (availabilityForDay == null) {
                isOpen = false;
            } else {
                isOpen = availabilityForDay.inRange(timeString);
            }
            
            System.out.println("Is open? " + isOpen);
    

    Output:

    Is open? true

    I am exploiting the fact that your time strings are in ISO 8601 format, and LocalTime parses this format as its default, that is, without any explicit formatter. The seconds are optional in the format, so both 00:00 and 02:39:00 are parsed.