I tried 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 have 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");
}
}
You perform two different operations here:
gives you a nicely formated way to output the difference between these dates (you have used the formatting options correctly).
will give you the same - but not so nicely formated (basically it just gives you the number of days between the LocalDates).