有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查两个日期周期是否重叠

  • 我有两个日期范围(开始1,结束1):>&燃气轮机;日期1及&;(开始2,结束2):>&燃气轮机;日期2
  • 我想看看这两个日期是否重叠

  • 我的流程图我假设“<;>;=”运算符可用于比较

    boolean isOverLaped(Date start1,Date end1,Date start2,Date end2) {
        if (start1>=end2 && end2>=start2 && start2>=end2) {
            return false;
        } else {
            return true;
        }
    }
    
  • 如有任何建议,将不胜感激

共 (4) 个答案

  1. # 1 楼答案

    你有两个间隔,i1和i2。关于时间间隔在时间上的相关性,有六种情况(至少在牛顿的世界观中),但只有两种情况是重要的:如果i1完全在i2之前,或者i1完全在i2之后;否则,两个间隔重叠(其他四种情况是i1包含i2,i2包含i1,i1包含i2的开始,i1包含i2的结束)。假设i1和i2属于Interval类型,具有日期字段beginTime和endTime。该函数是(注意,这里假设,如果I1同时开始I2结束,反之亦然),我们不考虑重叠和AsMe对于给定的间隔结束时间。在(开始时间)为假之前:

    boolean isOverlapped(Interval i1, Interval i2) {
        return i1.endTime.before(i2.beginTime) || i1.beginTime.after(i2.endTime);
    }
    

    在原始问题中,您指定DateTime而不是Date。在java中,日期既有日期也有时间。这与sql不同,在sql中,Date没有时间元素,而DateTime有时间元素。这是我在多年只使用java之后首次开始使用sql时遇到的一个困惑点。无论如何,我希望这个解释是有帮助的

  2. # 2 楼答案

    您可以使用Joda-Time进行此操作

    它提供了类^{},该类指定开始和结束实例,并可以检查与overlaps(Interval)的重叠

    差不多

    DateTime now = DateTime.now();
    
    DateTime start1 = now;
    DateTime end1 = now.plusMinutes(1);
    
    DateTime start2 = now.plusSeconds(50);
    DateTime end2 = now.plusMinutes(2);
    
    Interval interval = new Interval( start1, end1 );
    Interval interval2 = new Interval( start2, end2 );
    
    System.out.println( interval.overlaps( interval2 ) );
    

    印刷品

    true
    

    因为第一个间隔的结束介于第二个间隔的开始和结束之间

  3. # 3 楼答案

        //the inserted interval date is start with fromDate1 and end with toDate1
        //the date you want to compare with start with fromDate2 and end with toDate2
    
    if ((int)(toDate1 - fromDate2).TotalDays < 0 )
            { return true;}
    else
    {    
     Response.Write("<script>alert('there is an intersection between the inserted date interval and the one you want to compare with')</script>");
                return false;
            }
    
    if ((int)(fromDate1 - toDate2).TotalDays > 0 )
            { return true;}
    else
    {    
     Response.Write("<script>alert('there is an intersection between the inserted date interval and the one you want to compare with')</script>");
                return false;
            }
    
  4. # 4 楼答案

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime(); 
    }