时间比较

时间:2010-02-22 08:06:33

标签: java time comparison

我有hh:mm的时间,用户必须以该格式输入。

但是,我想比较时间(例如11:22)是在上午10点到下午6点之间吗?但是我如何比较呢?

11 个答案:

答案 0 :(得分:52)

Java(还)没有一个好的内置Time类(它有一个用于JDBC查询,但这不是你想要的)。

一种选择是使用JodaTime API及其LocalTime类。

只使用内置的Java API,您就会遇到java.util.Date。您可以使用SimpleDateFormat来解析时间,然后使用Date比较函数来查看它是在其他时间之前还是之后:

SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");

try {
    Date userDate = parser.parse(someOtherDate);
    if (userDate.after(ten) && userDate.before(eighteen)) {
        ...
    }
} catch (ParseException e) {
    // Invalid date was entered
}

或者您可以使用一些字符串操作,也许是正则表达式来提取小时和分钟部分,将它们转换为数字并进行数值比较:

Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
    String hourString = m.group(1);
    String minuteString = m.group(2);
    int hour = Integer.parseInt(hourString);
    int minute = Integer.parseInt(minuteString);

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

这完全取决于你想要完成的任务。

答案 1 :(得分:13)

使用Java 8+,您可以使用新的Java时间API:

  • 解析时间:

    LocalTime time = LocalTime.parse("11:22")
    
  • 进行日期比较,您有LocalTime::isBeforeLocalTime::isAfter - 请注意这些方法是严格的

所以问题就像:

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.
}

对于包容性开始但是独占结束(半开),请使用此行。

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

答案 2 :(得分:5)

示例:

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

答案 3 :(得分:4)

从您的陈述中,您似乎只想写:

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

如果您已经有时间,这是微不足道的。但你肯定还在问别的什么吗?

答案 4 :(得分:2)

以下假设您的小时和分钟分别存储为名为hhmm的变量中的整数。

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

答案 5 :(得分:2)

import java.util.Calendar;

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

答案 6 :(得分:2)

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)

答案 7 :(得分:2)

亚当在他的回答中解释得很好 但我用这种方式。我认为这是理解java中时间比较的最简单方法

首先创建3个日历对象,仅设置您的时间,小时和分钟。

然后获得该时间的GMT毫秒并简单地进行比较。

实施例。

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 ");
    }

输出将如下所示:

chechDateTime : 1397238720000
startDateTime 1397233800000
endDateTime 1397263920000
In between 

答案 8 :(得分:1)

我正在以这种格式使用这个类的时间“hh:mm:ss”你可以使用它与“hh:mm:00”(零秒)作为你的例子。这是完整的代码。它具有比较和功能之间,还检查时间格式(如果时间无效并抛出TimeException)。希望您可以使用它或根据您的需要进行修改。

时间等级:

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类:

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);
    }

}

答案 9 :(得分:1)

        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;
        }

答案 10 :(得分:0)

您可以使用Java Date类中的compareTo()方法

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

返回值:该函数提供以下指定的三个返回值:

如果参数Date等于此Date,则返回值0。 如果此Date在Date参数之前,则返回小于0的值。 如果此Date在Date参数之后,则返回大于0的值。