首页 > 解决方案 > java中月份两个日期之间的差异

问题描述

关于计算月份的查询,但有一些条件。使用 Joda 日期时间或日期工具。

Start Date : 01/01/2018
End Date : 31/12/2020

上述日期之间的总期间差异:36 months and 0 days 总计month =36

Start Date : 01/01/2018
End Date : 02/01/2021

上述日期之间的总期间差异:36 months and 2 days。如果还有天数,则考虑单月。所以total month 36+1= 37

 Date issueDate1=03/06/2017;  
     Date dateTo1=02/06/2020;


int investmentPeriod = Months.monthsBetween(issueDate1, dateTo1).getMonths();

上面几个月的jodacoming 35是错误的。

开始日期=23/06/2017;
日期结束=06/07/2017;

这里相差不到一个月。所以它被认为是单月。

标签: javadatetimejodatime

解决方案


 ZoneId defaultZoneId = ZoneId.systemDefault();
           String issueDate1="01/01/2017";  
            Date issueDate2=new SimpleDateFormat("dd/MM/yyyy").parse(issueDate1);
            String dateTo1="31/12/2018";  
            Date dateTo2=new SimpleDateFormat("dd/MM/yyyy").parse(dateTo1);

这里年月日很容易找到。这给出了所有问题的答案。

            Instant instant = issueDate2.toInstant();
            LocalDate localDatestart = instant.atZone(defaultZoneId).toLocalDate();

            Instant instant1 = dateTo2.toInstant();
            LocalDate localDateend = instant1.atZone(defaultZoneId).toLocalDate().plusDays(1);

        Period diff = Period.between(localDatestart, localDateend);

         System.out.printf("\nDifference is %d years, %d months and %d days old\n\n", 
                        diff.getYears(), diff.getMonths(), diff.getDays());

推荐阅读