Add year to Java Calendar doesn't work -
please enlight me on :
i'm trying add 10 years current date substract expiration date return 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 debug this, calendar stay @ current year.
anyone ?
you have problem int / long conversion: 365 * 24 * 60 * 60 * 1000 evaluates 31536000000 , therefore exceeds integer.max_value
2147483647 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 ); }
Comments
Post a Comment