Search code examples
javazoneddatetime

Checking if a ZonedDateTime is between a certain time


I am getting the time and date of a location with the code below

        ZoneId zoneId = ZoneId.of("America/New_York");
        ZonedDateTime dateAndTimeForAccount = ZonedDateTime.ofInstant(now, zoneId);
        System.out.println(dateAndTimeForAccount);

How can I check if dateAndTimeForAccount is between 6am to 10am?


Solution

  • One possible solution could be to use a ValueRange.

    NOTE: the below solution will result in true for 10:59 (see "Corner case output" at the very bottom:

    ZoneId zoneId = ZoneId.of("America/New_York");
    ZonedDateTime dateAndTimeForAccount = ZonedDateTime.ofInstant(now, zoneId);
    System.out.println(dateAndTimeForAccount);
    
    ValueRange hourRange = ValueRange.of(8, 10);
    System.out.printf("is hour (%s) in range [%s] -> %s%n", 
            dateAndTimeForAccount.getHour(),
            hourRange, 
            hourRange.isValidValue(dateAndTimeForAccount.getHour())
    );
    

    example output

    2017-01-11T07:34:26.932-05:00[America/New_York]
    is hour (7) in range [8 - 10] -> false
    

    edit: The snippet guides as an example for the suggested solution. It's not a full solution and as visible in the code it only makes a check on the hour part.

    Corner case output: results in true for 10:59:

    2017-01-11T10:59:59.999-05:00[America/New_York]
    is hour (10) in range [8 - 10] -> true