【问题标题】:Time comparison时间比较
【发布时间】:2011-01-19 13:19:14
【问题描述】:

我在hh:mm 有一个时间,它必须由用户以该格式输入。

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

【问题讨论】:

  • 放上你目前写的代码
  • if (hourFrom >=10 && hourFrom 18 && hourFrom
  • 我使用日历类将时间转换为 dateTime,然后获取该日期的 gmt 毫秒,然后比较该毫秒。看看我的回答。

标签: java time comparison


【解决方案1】:

我不懂 Java,但在 Kotlin 中我们现在有 coerceIn

public fun <T : Comparable<T>> T.coerceIn(
    range: ClosedRange<T>
): T

确保该值在指定范围内。

返回: 如果它在范围内,则为该值;如果该值小于 range.start,则为 range.start;如果该值大于 range.endInclusive,则为 range.endInclusive。

【讨论】:

    【解决方案2】:
            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;
            }
    

    【讨论】:

      【解决方案3】:

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

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

      返回值:该函数给出以下指定的三个返回值:

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

      【讨论】:

      • 感谢您的贡献。除了 Date 类早已过时,我相信您所说的已经在接受的答案中。你贡献了什么新东西?
      【解决方案4】:

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

      【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        【解决方案6】:

        亚当在他的回答中解释得很好 但是我用的是这种方式。我认为这是理解 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 
        

        【讨论】:

          【解决方案7】:
          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)
          

          【讨论】:

            【解决方案8】:

            我正在以这种格式“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】:
              import java.util.Calendar;
              
              Calendar cal = Calendar.getInstance();
              int currentHour = cal.get(Calendar.HOUR);
              if (currentHour > 10 && currentHour < 18) {
                  //then rock on
              }
              

              【讨论】:

                【解决方案10】:

                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) 不错的答案。如果您提供使用 LocalTime 的示例会更好,以便读者可以与其他方法进行比较。
                • 如果间隔是 18:00 - 2:00 怎么办,所以在这里我们将检查:if(hour &gt;= 18 &amp;&amp; hour &lt;= 2) 这永远不会是真的
                • +1 谢谢。我只是想补充一下,如果您需要使用 am,pm 您只需将解析器定义替换为 SimpleDateFormat parser = new SimpleDateFormat("hh:mm aa");
                • 如果someOtherDate == currentDate 例如,当前日期由new Date() 给出,它将不起作用,因为 SimpleDateFormat 解析器将返回 1970 年的某个日期。
                • 这个响应没有通过所有的测试用例!!
                【解决方案11】:

                示例:

                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

                【讨论】:

                  【解决方案12】:

                  从你的陈述看来,你只是想写:

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

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

                  【讨论】:

                  • 如果你看到上面的代码,我希望它也能检测到 18:01 到 18:59 之间,它现在似乎不起作用。
                  • 你应该说“到晚上 7 点”。只需将 18 更改为 19 即可。
                  猜你喜欢
                  • 2012-12-29
                  • 1970-01-01
                  • 2012-03-26
                  • 2011-08-13
                  • 2015-12-12
                  • 2011-09-03
                  • 2012-07-09
                  • 1970-01-01
                  相关资源
                  最近更新 更多