-3

I'm asked to write an expiry method for a policy that expires in exactly one year after it's added. I already wrote the method that adds one year to the initial date it was added.

Now I'm trying to write another method that returns a boolean to see if Date A is past Date B. If it's past, it means it's expired, so it'll return true. Can someone help me out with the Syntax, not sure what to do here. Thank you

public ExpirablePolicy(float a, Date d){
    super(a);
    amount = a;
    expiryDate = new Date();
    GregorianCalendar aCalendar = new GregorianCalendar();
    aCalendar.add(Calendar.YEAR,1);
    expiryDate = aCalendar.getTime();
} 

public boolean isExpired(){
    //expiry method;
4

4 に答える 4

6

This can be done with Date.before() or Date.after():

if (d.after(expiryDate)) { ... }

or

if (!d.before(expiryDate)) { ... }

The first comparison evaluates to true is d is strictly greater than expiryDate. The second evaluates to true if d is greater than or equal to expiryDate.

The same effect can be achieved with Date.compareTo().

于 2013-02-06T15:36:12.503 に答える
1

これを試して:

public boolean isExpired(Date a, Date b) {
    return a.before(b);
}
于 2013-02-06T15:38:29.433 に答える
1

java.util.Date を確認してください。これには、compareTo というメソッドがあります。

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#compareTo(java.util.Date)

于 2013-02-06T15:38:46.163 に答える
0

Date.compareTo(Date)メソッドを使用するだけです。

public boolean isExpired(Date d1, Date d2) {
    return d1.compareTo(d2) > 0;
}
于 2013-02-06T15:38:00.897 に答える