Search code examples
javadatemillisecondsjdatechooser

Incrementing date by 18years in java


1.I want to set the setMaxSelectableDate=18years in JDateChooser so i provided it the date by incrementing milliseconds but how should i increment it by 18years.
2.Incrementing by 18years the calculation comes out to be 365*18*24*60*60*1000=56764800000 which gives me error integer number to large.

 Date max=new Date();
Date oth1=new Date(max.getTime() + (365*18*24*60*60*1000));  //days*hours*minutes*seconds*milliseconds
SimpleDateFormat maxdateFormatter1 = new SimpleDateFormat("MMM d,yyyy hh:mm:ss a");
String maxdate=maxdateFormatter1.format(oth1);  
DateChooser_V1.setMaxSelectableDate(new java.util.Date(maxdate));

Solution

  • Let java.util.Calendar do this work for you:

    Calendar c = Calendar.getInstance();
    c.setTime(oldDate);
    c.add(Calendar.YEAR, 18);
    Date newDate = c.getTime();
    

    Which takes care of leap years, historical GMT offset changes, historical Daylight Saving Time schedule changes etc.