2016-11-24 17 views
0

我花了數小時思考這個問題。 我需要寫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。我的老師告訴我有一種方法可以做到,但我真的不知道如何,我花了太多時間在這個上。有沒有辦法?

+1

['java.util.Date.before(日期時)'](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) –

+1

我我不允許使用它 – Edmond

+0

你能不能只檢查日/月/年是否等於getDay/getMonth/getYear並返回正確的值? – Mogzol

回答

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

但是如果day = 31?天+ 1 = 32 – Edmond

+0

@愛德蒙有什麼關係? 32仍然大於31,你的'之前'仍然會工作。 – Mogzol

+0

好吧,只要它有效,我會用它 – Edmond

0

好了,這是你的作爲@Mogzol提到的簡單邏輯(在你的情況下,而不是int - >日期),

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 =假& isAfter =假

BEFORE:isBefore =假& isAfter =真

AFTER:isBefore =真& isAfter =假

在這裏的複雜性是必須建立一個邏輯,始終保持您的日期有效,就像在您的31 + 1情況下一樣,

您可以使用此處的任何想法how to increment a day by 1

簡單的一種是,

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

我找到了正確的代碼,之後方法。之前的方法保持不變。

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

使用-1,0和1日前T之間區分,相同和日期即在

  1. 「-1」 - 如果給定日期之前
  2. 「0」 - 如果給定的日期是同
  3. 「1」 - 如果給定日期後

然後你可以使用該功能在其他方法和更新您的狀態像

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