我需要保持第一次迭代的开始日期不变,并添加带有单位的结束日期,并且迭代应该发生,直到开始日期早于结束数据。
示例:
开始日期 (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 的日期/时间 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
或数组进行排序
关于java - 以恒定单位添加日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36052372/