2

我想在我的代码中计算出下一个付款日期。我有一个开始日期,我有一个付款频率,可以是 DAY、WEEK、MONTH 或 YEAR。因此,如果开始日期为 2009 年 2 月 10 日并且付款频率为 MONTH,当前日期为 2009 年 11 月 13 日,则下一个付款日期为 2009 年 12 月 10 日

我已经使用 JDK 数据类编写了一些丰富的代码来解决这个问题。但是我们已将系统的其他部分移至 Joda,因此我想将此代码迁移到。

那么有没有 Joda 大师知道如何轻松做到这一点?

4

2 回答 2

4

这是一种蛮力方法(忽略工作日等)。请注意,您不能只是重复添加期间,如(1 月 30 日 + 1 个月)+ 1 个月!= 1 月 30 日 + 2 个月。

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);
        }
    }
}

可能有更少的蛮力方法来做到这一点 - 特别是如果你不必能够完全任意地进行一段时间 - 但这可能是最简单的解决方案。

于 2009-11-13T08:02:48.293 回答
0

只是把评论放在一起

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));
}
于 2013-11-08T09:26:31.023 回答