Java中月份中两个日期之间的差异

问题描述:

有关计算月份的查询,但具有某些条件。
,并带有Joda日期时间或日期实用工具。

Query regarding calculate months but with some conditions. with Joda Date-time or date util.

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

上述日期之间的总期间差: 36月份和0天
,所以总计 month = 36

Total Period difference between above date: 36 months and 0 days so total month =36

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

上述日期之间的总期间差: 36个月和2天
如果还有剩余天数,则考虑为一个月。
所以总月数36 + 1 = 37

Total Period difference between above date: 36 months and 2 days. if there are days remaining then it consider single month. so total month 36+1= 37

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


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

在以上月份,乔达(Joda)的收入为 35

By joda above months are coming 35 which is wrong.

日期开始= 2017年6月23日;

日期结束= 2017年7月7日;

Date start=23/06/2017;
Date end=06/07/2017;

这里相差不到一个月。

here difference less than a month . so it consider as single month.

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

在这里年月日很容易找到。这给了所有问题一个答案。

here year month days can find easily.This giving ans of all question.

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