Friday, 11 May 2007

Oracle ADF How to get the Date after n days and calculate the difference between two dates

I have used this little code fragment many times and each time I try to remember where -- and in which file -- was the last.

I guess that if I put it here, I will limit my search space significantly :-)

import oracle.jbo.domain.Date;
import oracle.jbo.domain.Number;
import java.sql.Timestamp;

...
static final long MILI_SECONDS_PER_DAY = 86400000;

    /**
     * @param startDate initial date to start counting from
     * @param nDays number of days can be begative
     * @return a Date object nDays after startdate
     */
    public static Date dateAfterNDays( Date startDate, int nDays)
    {
       if (startDate == null)
           startDate = new Date(Date.getCurrentDate());  // assume today

       Timestamp ts = startDate.timestampValue();
       long nextDatesSecs = ts.getTime() + (MILI_SECONDS_PER_DAY * nDays);
       return new Date( new Timestamp(nextDatesSecs));
    }

Here is an other example that calculates the number of days between two dates. The parameter dates are oracle.jbo.domain.Date and the return type is an oracle.jbo.domain.Number.

    /**
     * return the number of days between two dates
     */

    private Number dateDifference(InDays Date startDate, Date endDate)
    {
       if (startDate == null)
           startDate = new Date(Date.getCurrentDate()); // assume today

       if (endDate == null)
            endDate = new Date(Date.getCurrentDate());  // asume today again

       Timestamp tsStart = startDate.timestampValue();
       Timestamp tsEnd = endDate.timestampValue();

       long ndays = (tsEnd.getTime() - tsStart.getTime()) / MILI_SECONDS_PER_DAY;

       return new Number(ndays);
    }

No comments :