使用joda时间无法在两个日期之间获得正确的差异

时间:2017-04-11 09:18:49

标签: java jodatime

我试图使用joda时间来区分这两个日期,但不知怎的,我无法得到确切的区别。

        LocalDate endofCentury = new LocalDate(2014, 01, 01);

        LocalDate now = LocalDate.now(); //2017-04-11

        Period diff = new Period(endofCentury, now); 

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

差异应该是 3年,3个月,10天,但我 3年,3个月和3天

不确定我错过了什么,请帮助我。

由于

1 个答案:

答案 0 :(得分:1)

使用带有3个参数的构造函数:

Period diff = new Period(endofCentury, now, PeriodType.yearMonthDay());

包含2个参数(from,to)的构造函数包含周数。

修改后的代码输出:

Period diff = new Period(endofCentury, now);
System.out.printf("Difference is %d years, %d months and %d weeks and %d days old",
                diff.getYears(), diff.getMonths(),diff.getWeeks(), diff.getDays());

给出输出:

  

差异是3年,3个月,1周和3天

但是使用指定的持续时间字段(第3个参数):

Period diff = new Period(endofCentury, now, PeriodType.yearMonthDay());
System.out.printf("Difference is %d years, %d months and %d weeks and %d days old",
            diff.getYears(), diff.getMonths(),diff.getWeeks(), diff.getDays());

你得到:

  

差异是3年,3个月,0周和10天

请参阅:http://joda-time.sourceforge.net/apidocs/org/joda/time/PeriodType.html