Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add year to Java Calendar doesn't work

Tags:

java

calendar

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 ?

like image 493
codea Avatar asked Oct 07 '10 15:10

codea


3 Answers

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 );
        } 
like image 150
stacker Avatar answered Nov 18 '22 23:11

stacker


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();
like image 27
BalusC Avatar answered Nov 18 '22 23:11

BalusC


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!

like image 5
Bryan James Avatar answered Nov 18 '22 23:11

Bryan James