[java] Time comparison

I have a time in hh:mm and it has to be entered by the user in that format.

However, I want to compare the time (eg. 11:22) is it between 10am to 6pm? But how do I compare it?

This question is related to java time comparison

The answer is


From your statement, it seems like you merely want to write:

if (10 >= hh && hh < 18) {
  ...
}

This is trivial if you are given the hours already. But surely you are asking something else?


The following assumes that your hours and minutes are stored as ints in variables named hh and mm respectively.

if ((hh > START_HOUR || (hh == START_HOUR && mm >= START_MINUTE)) &&
        (hh < END_HOUR || (hh == END_HOUR && mm <= END_MINUTE))) {
    ...
}

example:

import java.util.*;   
import java.lang.Object;   
import java.text.Collator;   
public class CurrentTime{   
  public class CurrentTime   
{   
    public static void main( String[] args )   
    {   
        Calendar calendar = new GregorianCalendar();   
        String am_pm;   
        int hour = calendar.get( Calendar.HOUR );   
        int minute = calendar.get( Calendar.MINUTE );   
        // int second = calendar.get(Calendar.SECOND);   
        if( calendar.get( Calendar.AM_PM ) == 0 ){   
            am_pm = "AM";   
            if(hour >=10)   
                System.out.println( "welcome" );   
        }               
        else{   
            am_pm = "PM";   
            if(hour<6)   
                System.out.println( "welcome" );   
        }   

        String time = "Current Time : " + hour + ":" + minute + " " + am_pm;   
        System.out.println( time );    
    }   
}  

Source


package javaapplication4;

import java.text.*;
import java.util.*;

/**
 *
 * @author Stefan Wendelmann
 */
public class JavaApplication4
{
    private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) throws ParseException
  {
    SimpleDateFormat parser = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss.SSS");
    Date before = parser.parse("01.10.1990 07:00:00.000");
    Date base = parser.parse("01.10.1990 08:00:00.000");
    Date after = parser.parse("01.10.1990 09:00:00.000");

    printCompare(base, base, "==");
    printCompare(base, before, "==");
    printCompare(base, before, "<");
    printCompare(base, after, "<");
    printCompare(base, after, ">");
    printCompare(base, before, ">");
    printCompare(base, before, "<=");
    printCompare(base, base, "<=");
    printCompare(base, after, "<=");
    printCompare(base, after, ">=");
    printCompare(base, base, ">=");
    printCompare(base, before, ">=");

  }

  private static void printCompare (Date a, Date b, String operator){
    System.out.println(sdf.format(b)+"\t"+operator+"\t"+sdf.format(a)+"\t"+compareTime(a, b, operator));
  }

  protected static boolean compareTime(Date a, Date b, String operator)
  {
    if (a == null)
    {
      return false;
    }
    try
    {
      //Zeit aus Datum holen
// The Magic happens here i only get the Time out of the Date Object
      SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.SSS");
      a = parser.parse(parser.format(a));
      b = parser.parse(parser.format(b));
    }
    catch (ParseException ex)
    {
      System.err.println(ex);
    }
    switch (operator)
    {
      case "==":
        return b.compareTo(a) == 0;
      case "<":
        return b.compareTo(a) < 0;
      case ">":
        return b.compareTo(a) > 0;
      case "<=":
        return b.compareTo(a) <= 0;
      case ">=":
        return b.compareTo(a) >= 0;
      default:
        throw new IllegalArgumentException("Operator " + operator + " wird für Feldart Time nicht unterstützt!");

    }
  }

}



run:
08:00:00.000    ==  08:00:00.000    true
07:00:00.000    ==  08:00:00.000    false
07:00:00.000    <   08:00:00.000    true
09:00:00.000    <   08:00:00.000    false
09:00:00.000    >   08:00:00.000    true
07:00:00.000    >   08:00:00.000    false
07:00:00.000    <=  08:00:00.000    true
08:00:00.000    <=  08:00:00.000    true
09:00:00.000    <=  08:00:00.000    false
09:00:00.000    >=  08:00:00.000    true
08:00:00.000    >=  08:00:00.000    true
07:00:00.000    >=  08:00:00.000    false
BUILD SUCCESSFUL (total time: 0 seconds)

With Java 8+, you can use the new Java time API:

  • to parse the time:

    LocalTime time = LocalTime.parse("11:22")
    
  • to do date comparisons, you have LocalTime::isBefore and LocalTime::isAfter - note that these methods are strict

So you problem would be as simple as:

public static void main(String[] args) {
  LocalTime time = LocalTime.parse("11:22");
  System.out.println(isBetween(time, LocalTime.of(10, 0), LocalTime.of(18, 0)));
}

public static boolean isBetween(LocalTime candidate, LocalTime start, LocalTime end) {
  return !candidate.isBefore(start) && !candidate.isAfter(end);  // Inclusive.
}

For inclusive beginning but exclusive ending (half-open), use this line.

return !candidate.isBefore(start) && candidate.isBefore(end);  // Exclusive of end.

        String timeRange = "12:24-13:24";
        String[] timeR = timeRange.trim().split("-");
        
        // java 8
        LocalTime start = LocalTime.parse(timeR[0].trim());
        LocalTime end = LocalTime.parse(timeR[1].trim());
        LocalTime current = LocalTime.now();
        LocalTime currentHM = LocalTime.parse(current.getHour()+":"+current.getMinute());
        
        
        if(!currentHM.isBefore(start) && !currentHM.isAfter(end)) {
            return true;
        }else {
            return false;
        }

You can use the compareTo() method from Java Date class

public int result = date.compareTo(Date anotherDate); 

Return Value: The function gives three return values specified below:

It returns the value 0 if the argument Date is equal to this Date. It returns a value less than 0 if this Date is before the Date argument. It returns a value greater than 0 if this Date is after the Date argument.


I am using this class for time in this format "hh:mm:ss" u can use it with "hh:mm:00" (zero seconds) for your example. Here is the complete code. It has compare and between function and also checks the time format (in case of invalid time and throws TimeException). Hope you can use it or modify it for your needs.

Time class:

package es.utility.time;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author adrian
 */
public class Time {

    private int hours; //Hours of the day
    private int minutes; //Minutes of the day
    private int seconds; //Seconds of the day
    private String time; //Time of the day

    /**
     * Constructor of Time class
     *
     * @param time
     * @throws TimeException if time parameter is not valid
     */
    public Time(String time) throws TimeException {
        //Check if valid time
        if (!validTime(time)) {
            throw new TimeException();
        }
        //Init class parametars
        String[] params = time.split(":");
        this.time = time;
        this.hours = Integer.parseInt(params[0]);
        this.minutes = Integer.parseInt(params[1]);
        this.seconds = Integer.parseInt(params[2]);
    }

    /**
     * Constructor of Time class
     *
     * @param hours
     * @param minutes
     * @param seconds
     * @throws TimeException if time parameter is not valid
     */
    public Time(int hours, int minutes, int seconds) throws TimeException {
        //Check if valid time
        if (!validTime(hours, minutes, seconds)) {
            throw new TimeException();
        }
        this.time = timeToString(hours, minutes, seconds);
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;

    }

    /**
     * Checks if the sting can be parsed as time
     *
     * @param time (correct from hh:mm:ss)
     * @return true if ok <br/> false if not ok
     */
    private boolean validTime(String time) {
        String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(time);
        return m.matches();
    }

    /**
     * Checks if the sting can be parsed as time
     *
     * @param hours hours
     * @param minutes minutes
     * @param seconds seconds
     * @return true if ok <br/> false if not ok
     */
    private boolean validTime(int hours, int minutes, int seconds) {
        return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59;
    }

    /**
     * From Integer values to String time
     *
     * @param hours
     * @param minutes
     * @param seconds
     * @return String generated from int values for hours minutes and seconds
     */
    private String timeToString(int hours, int minutes, int seconds) {
        StringBuilder timeBuilder = new StringBuilder("");
        if (hours < 10) {
            timeBuilder.append("0").append(hours);
        } else {
            timeBuilder.append(hours);
        }
        timeBuilder.append(":");
        if (minutes < 10) {
            timeBuilder.append("0").append(minutes);
        } else {
            timeBuilder.append(minutes);
        }
        timeBuilder.append(":");
        if (seconds < 10) {
            timeBuilder.append("0").append(seconds);
        } else {
            timeBuilder.append(seconds);
        }
        return timeBuilder.toString();
    }

    /**
     * Compare this time to other
     *
     * @param compare
     * @return -1 time is before <br/> 0 time is equal <br/> time is after
     */
    public int compareTime(Time compare) {
        //Check hours
        if (this.getHours() < compare.getHours()) { //If hours are before return -1
            return -1;
        }
        if (this.getHours() > compare.getHours()) { //If hours are after return 1
            return 1;
        }
        //If no return hours are equeal
        //Check minutes
        if (this.getMinutes() < compare.getMinutes()) { //If minutes are before return -1
            return -1;
        }
        if (this.getMinutes() > compare.getMinutes()) { //If minutes are after return 1
            return 1;
        }
        //If no return minutes are equeal
        //Check seconds
        if (this.getSeconds() < compare.getSeconds()) { //If minutes are before return -1
            return -1;
        }
        if (this.getSeconds() > compare.getSeconds()) { //If minutes are after return 1
            return 1;
        }
        //If no return seconds are equeal and return 0
        return 0;
    }

    public boolean isBetween(Time before, Time after) throws TimeException{
        if(before.compareTime(after)== 1){
            throw new TimeException("Time 'before' is after 'after' time");
        }
        //Compare with before and after
        if (this.compareTime(before) == -1 || this.compareTime(after) == 1) { //If time is before before time return false or time is after after time
            return false;
        } else {
            return true;
        }
    }

    public int getHours() {
        return hours;
    }

    public void setHours(int hours) {
        this.hours = hours;
    }

    public int getMinutes() {
        return minutes;
    }

    public void setMinutes(int minutes) {
        this.minutes = minutes;
    }

    public int getSeconds() {
        return seconds;
    }

    public void setSeconds(int seconds) {
        this.seconds = seconds;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    /**
     * Override the toString method and return all of the class private
     * parameters
     *
     * @return String Time{" + "hours=" + hours + ", minutes=" + minutes + ",
     * seconds=" + seconds + ", time=" + time + '}'
     */
    @Override
    public String toString() {
        return "Time{" + "hours=" + hours + ", minutes=" + minutes + ", seconds=" + seconds + ", time=" + time + '}';
    }

}

TimeException class:

package es.utility.time;

/**
 *
 * @author adrian
 */
public class TimeException extends Exception {

    public TimeException() {
        super("Cannot create time with this params");
    }

    public TimeException(String message) {
        super(message);
    }

}

import java.util.Calendar;

Calendar cal = Calendar.getInstance();
int currentHour = cal.get(Calendar.HOUR);
if (currentHour > 10 && currentHour < 18) {
    //then rock on
}

Adam explain well in his answer But I used this way. I think this is easiest way to understand time comparison in java

First create 3 calender object with set your time only , Hour and min.

then get GMT milliseconds of that time and simply compare.

Ex.

Calendar chechDateTime = Calendar.getInstance();
chechDateTime.set(Calendar.MILLISECOND, 0);
chechDateTime.set(Calendar.SECOND, 0);
chechDateTime.set(Calendar.HOUR, 11);
chechDateTime.set(Calendar.MINUTE, 22);


Calendar startDateTime = Calendar.getInstance();
startDateTime.set(Calendar.MILLISECOND, 0);
startDateTime.set(Calendar.SECOND, 0);
startDateTime.set(Calendar.HOUR, 10);
startDateTime.set(Calendar.MINUTE, 0);

Calendar endDateTime = Calendar.getInstance();
endDateTime.set(Calendar.MILLISECOND, 0);
endDateTime.set(Calendar.SECOND, 0);
endDateTime.set(Calendar.HOUR, 18);
endDateTime.set(Calendar.MINUTE, 22);

 long chechDateTimeMilliseconds=chechDateTime.getTime().getTime();
 long startDateTimeMilliseconds=startDateTime.getTime().getTime();
 long endDateTimeMilliseconds=endDateTime.getTime().getTime();


System.out.println("chechDateTime : "+chechDateTimeMilliseconds);
System.out.println("startDateTime "+startDateTimeMilliseconds);
System.out.println("endDateTime "+endDateTimeMilliseconds);



if(chechDateTimeMilliseconds>=startDateTimeMilliseconds && chechDateTimeMilliseconds <= endDateTimeMilliseconds ){
       System.out.println("In between ");
    }else{
         System.out.println("Not In between ");
    }

Output will look like this :

chechDateTime : 1397238720000
startDateTime 1397233800000
endDateTime 1397263920000
In between 

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to comparison

Wildcard string comparison in Javascript How to compare two JSON objects with the same elements in a different order equal? Comparing strings, c++ Char Comparison in C bash string compare to multiple correct values Comparing two hashmaps for equal values and same key sets? Comparing boxed Long values 127 and 128 Compare two files report difference in python How do I fix this "TypeError: 'str' object is not callable" error? Compare cell contents against string in Excel