Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Calendar. After function is not returning expected result [duplicate]

Tags:

java

calendar

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?

like image 483
A Paul Avatar asked May 25 '26 15:05

A Paul


1 Answers

(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.

like image 185
peter.petrov Avatar answered May 28 '26 04:05

peter.petrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!