问题
i tired using java.time.Period
, and the results were different from my manual calculations by three days.
The weird thing here is when i divide the period into two periods , the results matches my manual calculations.
the second method is just like how i calculate the period manually.
is there something i missed ? is there a standard method or algorithm of calendar arithmetic ? and what's the algorithm used by java.time.Period
?
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class test2 {
public static void main(String[] args) {
LocalDate d1 = LocalDate.of(2014, 2, 14);
LocalDate d2 = LocalDate.of(2017, 8, 1);
Period p = Period.between(d1, d2);
//using period between the two dates directly
System.out.println("period between " + d1.toString() + " and " + d2.toString() + " is " + p.getYears()
+ " years " + p.getMonths() + " months " + p.getDays() + " Days");
//dividing the period into two parts
p = Period.between(LocalDate.of(2014, 3, 1), d2);
System.out
.println("period between " + d1.toString() + " and " + d2.toString() + " is " + p.getYears() + " years "
+ p.getMonths() + " months " + d1.until(LocalDate.of(2014, 3, 1), ChronoUnit.DAYS) + " Days");
}
}
回答1:
You perform two different operations here:
Period p = Period.between(d1, d2)
gives you a nicely formated way to output the difference between these dates (you have used the formatting options correctly).
d1.until(d2, ChronoUnit.DAYS)
will give you the same - but not so nicely formated (basically it just gives you the number of days between the LocalDates).
回答2:
The answer (period between 2014-02-14 and 2017-08-01 is 3 years 5 months 18 Days) is what you should expect:
- it's 3 years from
2014-02-14
to2017-02-14
- it's 5 months from
2017-02-14
to2017-07-14
- it's 18 days from
2017-07-14
to2017-08-01
The calculation proceeds from years to months to days. This allows you to calculate the number of years, months and days between 2014-02-14
and 2016-02-29
, which gives 2 years and 15 days.
If you try to calculate the days first you have problems determining the number of years, months and days between 2014-02-14
and 2016-02-29
, because there is no day 2014-02-29
- 14 days after 2014-02-14
its 2014-02-28
, 15 days after 2014-02-14
its 2014-03-01
.
来源:https://stackoverflow.com/questions/45905012/java-time-period-dividing-the-period-gives-wrong-results