Question

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));
Was it helpful?

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.

OTHER TIPS

You need to use a long. You can achieve this by adding an L to your number:

365L* ...

With JodaTime

DateTime in18Years = new DateTime( ).plusYears( 18 );

Here is how to convert to java.util.Date

Date in18Years = new DateTime( ).plusYears( 18 ).toDate( );

You cannot willy-nilly add seconds (or millseconds) and expect calendar calculations to come out right. Basically it takes some extra effort to account for all of those leap-years, leap seconds, and daylight savings shifts.

Until Java 1.8 comes out, use java.util.Calendar instead of java.util.Date, there are really good reasons that java.util.Date has practically everything in it deprecated. While it looks good in the beginning, with enough use you will find it often "just doesn't work (tm)".

 GregorianCalendar now = new GregorianCalendar();
 now.add(Calendar.YEAR, 18);

And that's assuming that you didn't overflow Integer.MAX_INT.

I would use a Calendar object to achieve this:

Calendar cal = Calendar.getInstance();
Date dt = new Date();
...
// Set the date value
...
cal.setTime(dt);
cal.add(Calendar.YEAR, +18);
dt = cal.getTime();

Hope this helps you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top