开发者

Best way to calculate next date from start plus frequency using joda time

开发者 https://www.devze.com 2022-12-11 03:09 出处:网络
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 fr

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 paym开发者_开发百科ent 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?


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.


Just putting together the comments

public static void main(String[] args) {
    LocalDate date = LocalDate.parse("03-10-2010",Constants.DEFAULT_DATE_FORMAT);

    Months gap = Months.monthsBetween(date,LocalDate.now());
    System.out.println(Months.monthsBetween(date,LocalDate.now()));
    System.out.println("Cycle Start " + date.plusMonths(gap.getMonths()));
    System.out.println("Cycle End " + date.plusMonths(gap.getMonths()+1));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消