Quoting [EMAIL PROTECTED]:

> 
> My favorite "Core Java" book proposes the "corejava.Day" class (see
> http://www.horstmann.com/corejava.html) which has
>      int daysBetween(Day b)
> method. Tt calcurates the number of days between 2 dates, rather than
> "years". Do you want the number of years in fraction ( like 1.43234 years)?
> 

this will get you the days:

    /**
     * @param d1 1st date
     * @param d2 2nd date
     * @returns number of days between dates d1 and d2 (abs; order is irrelevant)
     **/
    public static int daysBetween( Calendar d1 , Calendar d2 ){
        long d1ms = d1.getTime().getTime();
        long d2ms = d2.getTime().getTime();
        long days = (d2ms-d1ms)/(long) StdUnits.MS_PER_DAY;
        if (days < 0) days *= -1;
        return (int) days;
    } 

where MS_PER_DAY is just 60*24*60*1000;

getting from days -> years consistently is harder because of leap
years/centuries. A crude approach is:

 public static int yearsBetween( Calendar start , Calendar stop ){
        int p = 0;
        Calendar c = (Calendar) start.clone();
        do{
            c.add( Calendar.YEAR , 1 );
            p++;
        } while( c.before( stop ) );
        return p;
    }

hope this helps,

Graham

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to