Please enlight me on this :
I'm simply trying to add 10 years to the current date then substract an expiration date from it to return the number of years:
public int getMaxYears() {
int max = 0;
Calendar ten_year_later = Calendar.getInstance();
ten_year_later.setTime(new Date());
ten_year_later.add(Calendar.YEAR, 10);
Calendar expiration = Calendar.getInstance();
expiration.setTime(expiration_date);
max = (int) (ten_year_later.getTimeInMillis() - expiration.getTimeInMillis())/(365 * 24 * 60 * 60 * 1000);
return max;
}
When I debug this, the calendar always stay at the current year.
Anyone ?
You have a problem with int / long conversion: 365 * 24 * 60 * 60 * 1000
Which evaluates to 31536000000 and therefore exceeds Integer.MAX_VALUE
2147483647
This works:
public static void main(String[] args) {
Calendar ten_year_later = Calendar.getInstance();
System.out.println( ten_year_later.getTime() );
ten_year_later.setTime(new Date());
ten_year_later.add(Calendar.YEAR, 10);
System.out.println( ten_year_later.getTime() );
Calendar expiration = Calendar.getInstance();
expiration.setTime(expiration.getTime());
long max = (ten_year_later.getTimeInMillis() - expiration.getTimeInMillis())/(365 * 24 * 60 * 60 * 1000L);
System.out.println( "max " + max );
}
Your calculation of max
is wrong. An int
cannot hold a year in millis.
Rather replace it by
max = ten_year_later.get(Calendar.YEAR) - expiration.get(Calendar.YEAR);
Or better, use JodaTime:
DateTime tenYearsLater = new DateTime().plusYears(10);
DateTime expiration = new DateTime(expiration_date.getTime());
Period period = new Period(expiration, tenYearsLater);
return period.getYears();
Here's a simple example of what should work.
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(Calendar.YEAR, yearsToAdd);
Date retDate = cal.getTime();
Just remember to use a long to get the time in milliseconds!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With