2017-04-11 16 views
0

我想使用乔达时间来获得两个日期之间的差异,但不知何故,我无法获得确切的区别。使用乔达时间无法获得两个日期之间的正确区别

 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

使用构造与3个参数:

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

构造有两个参数的(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天

但带有指定的持续时间字段(第三个参数):

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

+0

感谢@杰罗姆。该解决方案为我工作。 –