A Paul
A Paul

Reputation: 8251

Java Calendar. After function is not returning expected result

I have written the below code

Calendar now = Calendar.getInstance();
Calendar expiry = Calendar.getInstance();
expiry.set(2014, 1, 15, 0, 0); 
now.after(expiry);

this is giving me false, today is 19th it should give true

Am I missing anything?

Upvotes: 2

Views: 394

Answers (1)

peter.petrov
peter.petrov

Reputation: 39477

(1) Month 1 is February, not January as you thought. Month 0 is for January.

(2) Also, I would call getTime() right before calling after() just to be on the safe side.

Calendar now = Calendar.getInstance();
Calendar expiry = Calendar.getInstance();
expiry.set(2014, 0, 15, 0, 0); 
expiry.getTime();
now.after(expiry);

Not sure if calling getTime() here is strictly needed though.

I am referring to this part of the JavaDoc.

set(f, value) changes calendar field f to value. In addition, it sets an
internal member variable to indicate that calendar field f has been changed.
Although calendar field f is changed immediately, the calendar's time value
in milliseconds is not recomputed until the next call to get(), getTime(),
getTimeInMillis(), add(), or roll() is made. Thus, multiple calls to set()
do not trigger multiple, unnecessary computations. As a result of changing
a calendar field using set(), other calendar fields may also change, depending
on the calendar field, the calendar field value, and the calendar system.
In addition, get(f) will not necessarily return value set by the call to
the set method after the calendar fields have been recomputed.
The specifics are determined by the concrete calendar class.

Upvotes: 2

Related Questions