Java Now isNowInInterval(String start, String end)

Here you can find the source of isNowInInterval(String start, String end)

Description

is Now In Interval

License

Apache License

Parameter

Parameter Description
start interval start
end interval end

Return

true true if the current hour is between

Declaration

public static boolean isNowInInterval(String start, String end) 

Method Source Code

//package com.java2s;
/*//from   w w w. j  a  v  a 2 s.  c  o m
 * Copyright 2013-2017 Simba Open Source
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {
    private static final String HOUR_VALIDATION_REGEX = "([01][0-9]|2[0-3]):[0-5][0-9]";
    private static SimpleDateFormat sdfHour;

    /**
     * @param start interval start
     * @param end   interval end
     * @return true    true if the current hour is between
     */
    public static boolean isNowInInterval(String start, String end) {
        return isHourInInterval(getCurrentHour(), start, end);
    }

    /**
     * @param target hour to check
     * @param start  interval start
     * @param end    interval end
     * @return true    true if the given hour is between
     */
    public static boolean isHourInInterval(String target, String start, String end) {
        if (!validateHour(target)) {
            throw new IllegalArgumentException("Please specify a valid target hour");
        }

        if (!validateHour(start)) {
            throw new IllegalArgumentException("Please specify a valid start hour");
        }

        if (!validateHour(end)) {
            throw new IllegalArgumentException("Please specify a valid end hour");
        }

        if (start.compareTo(end) <= 0) {
            return ((target.compareTo(start) >= 0) && (target.compareTo(end) <= 0));
        }

        return ((target.compareTo(start) <= 0) && (target.compareTo(end) >= 0));
    }

    public static String getCurrentHour() {
        return sdfHour.format(new Date());
    }

    public static boolean validateHour(String hour) {
        return hour != null && hour.matches(HOUR_VALIDATION_REGEX);
    }
}

Related

  1. getTimeNow()
  2. getTimeNow(Date theTime)
  3. getTimeNowAsString(String pattern)
  4. getTimeSubFromNowTime(String time)
  5. getValidDate(String unknownDate)
  6. makeUniqueName(final String[] knownNames, final String pattern)
  7. now()
  8. now()
  9. now()