java - 以恒定单位添加日期之间的差异

标签 java arrays unit-testing date

我需要保持第一次迭代的开始日期不变,并添加带有单位的结束日期,并且迭代应该发生,直到开始日期早于结束数据。

示例:

开始日期 (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”值就不会太难了。然后,您可以使用 ComparableComparator 将它们按某种 List 或数组进行排序

关于java - 以恒定单位添加日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36052372/

相关文章:

java - Java 中的按钮数组

c# - 是否有用于指定配置的 NUnit 测试用例属性

java - 为什么我的密码验证在 Java 中不起作用?

java - 有效 XML 上的 JAXP 解析错误

java - 使用 Java 中的传统 for 循环遍历堆栈

javascript - 通过深度索引访问数组元素

javascript - 检查 NaN 为真/假时出现问题

java - 从 Java 中的变量获取类

ios - 如何使用 RestKit Testing 测试此对象映射

java - 如何使用 ScalaCheck 测试 Java 程序?