我需要保持第一次迭代的开始日期不变,并添加带有单位的结束日期,迭代应该发生,直到开始日期在结束数据之前。
例:
开始日期 (1/1/2015) 和结束日期 (12/31/2015) 之间的差异为 12 个月
单位为4个月
那我应该得到
Contract Start date End date
1 1/1/2015 4/31/2015
2 5/1/2015 8/31/2015
3 9/1/2015 12/31/2015
我试过的代码:
private void contractDetails(List<PolicyPeriodFormulaType> policyPeriod ){
for (PolicyPeriodFormulaType policyPeriodFormulaType : policyPeriod) {
Date effectiveDateFrom = policyPeriodFormulaType.getEffectivePeriod().getEffectiveFrom();
Date effectiveDateTo = policyPeriodFormulaType.getEffectivePeriod().getEffectiveTo();
Instant effectiveFrom = effectiveDateFrom.toInstant();
ZonedDateTime zdt = effectiveFrom.atZone(ZoneId.systemDefault());
LocalDate fromDate = zdt.toLocalDate();
Instant effectiveTo = effectiveDateTo.toInstant();
ZonedDateTime zdt1 = effectiveTo.atZone(ZoneId.systemDefault());
LocalDate toDate = zdt.toLocalDate();
int unit = policyPeriodFormulaType.getUnits();
String unitMeasurement = policyPeriodFormulaType.getUnitOfMeasurement();
Period p = Period.between(fromDate,toDate);
int months = p.getMonths();
int years = p.getYears();
if(unitMeasurement.equalsIgnoreCase("Month")){
months = months+(years*12);
}
int duration = months/unit; // 12/4 = 3
int i =0;
while(fromDate.isBefore(toDate)){
fromDate=fromDate;
toDate=fromDate.plusMonths(unit);
fromDate=toDate.plusMonths(unit);
}
}
}
坦率地说,你应该以某种形式使用 Java 8 的 Date/Time API 或 Joda-Time,例如......
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate startDate = LocalDate.parse("01/01/2015", dtf);
LocalDate endDate = LocalDate.parse("12/31/2015", dtf);
LocalDate date = startDate;
Period period = Period.parse("P4M");
// or
//Period period = Period.ofMonths(4);
// or
//Period period = Period.of(0, 4, 0);
while (date.isBefore(endDate)) {
LocalDate to = date.plus(period);
System.out.println(dtf.format(date) + " - " + dtf.format(to.minusDays(1)));
date = to;
}
哪些打印
01/01/2015 - 04/30/2015
05/01/2015 - 08/31/2015
09/01/2015 - 12/31/2015
由此,创建一个容器类(即Contract
样式类)来包含 to-from 值并不难。然后,您可以使用Comparable
或Comparator
将它们按某种List
或数组进行排序