如何检查日期是在之前还是之后

时间:2016-11-24 02:34:25

标签: java

我花了好几个小时思考这件事。 我需要编写2种方法。之前和之后。以后只能使用前一种方法。 我写了代码:

public boolean before(Date d) 
{
    if(getYear()<d.getYear() || (getYear()==d.getYear() && getMonth()<d.getMonth()) 
       || (getYear()==d.getYear() && getMonth()==d.getMonth() && getDay()<d.getDay()))
    {
     return true;
    }
return false;
}

然后:

public boolean after(Date d)
{
   if(!before(d))
   {
      return true;
   }
return false;
}

但问题是,在返回false之前的同一天,返回true后我需要它们返回false。我的老师告诉我,有办法做到这一点,但我真的不知道如何,我花了太多时间在这上面。有办法吗?

4 个答案:

答案 0 :(得分:0)

假设day与您的日期一样精确,您可以

public boolean after(int day, int month, int year)
{
   if(!before(day + 1, month, year))
   {
      return true;
   }
   return false;
}

此外,由于您只是返回一个布尔值,可以缩短为

public boolean after(int day, int month, int year)
{
   return !before(day + 1, month, year);
}

答案 1 :(得分:0)

好的,这是你的简单逻辑,如@Mogzol所提到的(在你的情况下,而不是int - &gt; date),

static int j = 1;

public static void main(String[] args) {
    System.out.println("EQUAL : isBefore  = " + before(1) + " & isAfter = " + after(1));
    System.out.println("BEFORE : isBefore = " + before(0) + " & isAfter = " + after(0));
    System.out.println("AFTER : isBefore = " + before(2) + " & isAfter = " + after(2));
}

public static boolean before(int i) {
    return i - j > 0;
}

public static boolean after(int i) {
    return !before(i+1);
}
  

EQUAL:isBefore = false&amp; isAfter = false

     

之前:isBefore = false&amp; isAfter = true

     

之后:isBefore = true&amp; isAfter = false

这里的复杂性是你必须建立一个逻辑来保持你的日期有效,就像你的31 + 1案例一样,

你可以使用这里提出的任何想法how to increment a day by 1

最简单的是,

public boolean after(Date d)
{
   return !before(new Date (d.getTime()+24*60*60*1000));
}

答案 2 :(得分:0)

我找到了after方法的正确代码。之前的方法保持不变。

public boolean after(Date other)
{
  if(this.before(other)==true)
  {
     return false;
  }
  else if(this.before(other)==other.before(this))  //same day.
  {
     return false;
  }
return true;
}

答案 3 :(得分:0)

使用-1,0和1 t区分之前,之后和之后,即

  1. “ -​​ 1” - 如果给定日期在
  2. 之前
  3. “0” - 如果给定日期相同
  4. “1” - 如果给定日期在
  5. 之后

    然后您可以在其他方法中使用该功能并更新您的条件,如

    public boolean after(Date d)
    {
       if(before(d) == 1)
       {
          return true;
       }
    return false;
    }