tags:

views:

287

answers:

1

Hi all

I want to work out the next payment date in my code. I have a start date and i have a payment frequency which can be DAY, WEEK, MONTH or YEAR. So if the start date was 10 FEB 2009 and had a payment frequency of MONTH and the current date is 13 NOV 2009 then the next payment date would be 10 DEC 2009

I have already written some meaty code using JDK data classes to work this out. But we have move other parts of the system to Joda and so i would like to migrate this code to.

So does any Joda guru know how to do it easily?

+2  A: 

Here's a brute force method (ignoring working days etc). Note that you can't just repeatedly add the period, as (Jan 30th + 1 month) + 1 month != Jan 30th + 2 months.

import org.joda.time.LocalDate;
import org.joda.time.Period;

public class Test {
    public static void main(String[] args) {
        LocalDate start = new LocalDate(2009, 2, 10);
        LocalDate now = new LocalDate(2009, 11, 13);
        System.out.println(next(start, Period.months(1), now));
    }

    public static LocalDate next(LocalDate start, Period period, LocalDate now) {
        Period current = Period.ZERO;
        while (true) {
            LocalDate candidate = start.plus(current);
            if (candidate.isAfter(now)) {
                return candidate;
            }
            current = current.plus(period);
        }
    }
}

It's possible that there are less brute-force ways of doing it - particularly if you don't have to be able to take a completely arbitrary period - but this is probably the simplest solution.

Jon Skeet
Thanks Jon. that has given me some ideas. I was thinking about this way what do you think.The example assumes the frequency is monthsFirst i get the months between the two dates start and todayint monthsCount = Months.monthsBetween(start,today).getMonths();then i add the months maybe like this:nextDate = start.plus(Period.months(monthsCount + 1)) whould that work ?
Peter Delahunty
I would suggest using monthsBetween to get an initial "guess" (x say) - and then try that x-1, x and x+1. That's cheap to do, and it avoids subtle corner cases.
Jon Skeet