How to compare current time with time range?

  • Convert the two strings to Date objects (which are also time objects) Create a new Date object.
  • This will contain the current time.
  • Use the Date.before() and Date.after() methods to determine if you are in the time interval.

EDIT: You should be able to use this directly (and no deprecated methods)

public static final String inputFormat = "HH:mm";

private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;

private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";

SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);

private void compareDates(){
    Calendar now = Calendar.getInstance();

    int hour = now.get(Calendar.HOUR);
    int minute = now.get(Calendar.MINUTE);

    date = parseDate(hour + ":" + minute);
    dateCompareOne = parseDate(compareStringOne);
    dateCompareTwo = parseDate(compareStringTwo);

    if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
        //yada yada
    }
}

private Date parseDate(String date) {

    try {
        return inputParser.parse(date);
    } catch (java.text.ParseException e) {
        return new Date(0);
    }
}

This is what I used as simple function and it worked for me:

public static boolean isTimeWith_in_Interval(String valueToCheck, String startTime, String endTime) {
    boolean isBetween = false;
    try {
        Date time1 = new SimpleDateFormat("HH:mm:ss").parse(startTime);

        Date time2 = new SimpleDateFormat("HH:mm:ss").parse(endTime);

        Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);

        if (time1.before(d) && time2.after(d)) {
            isBetween = true;
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return isBetween;
}

SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");

Date EndTime = dateFormat.parse("10:00");

Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));

if (CurrentTime.after(EndTime))
{
    System.out.println("timeeee end ");
}

Don't forget to surrounded with a try catch block

Tags:

Time

Java