I want to make a method where I enter a LocalDate and it returns the number of days elapsed, first I am doing it in the main class to see if I agree with the logic, results and other things that should be taken into account when operating dates but I already got a little confused when the date that I input as a parameter is greater than the current date that I use to perform the calculations.
LocalDate fecha1=LocalDate.of(1990,8,18);
LocalDate fecha2=LocalDate.now();
System.out.println("fech1: "+fecha1);
System.out.println("fech2: "+fecha2);
int anioACT = fecha2.getYear();
int mesACT = fecha2.getMonthValue();
int diaACT = fecha2.getDayOfMonth();
int resAnio = 0;
int resDia = fecha2.getDayOfMonth() - fecha1.getDayOfMonth() + 1;
int resMes = fecha2.getMonthValue() - fecha1.getMonthValue() -1;
if(fecha2.getYear() > fecha1.getYear()) {
if(fecha2.getMonthValue() == fecha1.getMonthValue()) {
if(fecha2.getDayOfMonth() == fecha1.getDayOfMonth()) {
resAnio = fecha2.getYear() - fecha1.getYear();
}
}else {
resAnio = fecha2.getYear() - fecha1.getYear() - 1;
}
}
System.out.println("dias: "+resDia);
System.out.println("meses: "+resMes);
System.out.println("anios: "+resAnio);
I add 1 to the days after the operation between them, since I want that day to also be part of the result; in case the entered month is greater than the current month, I thought of subtracting the difference that exists so that a month is fulfilled and also subtracting a month from the entered months.
Can you help me to find a feasible solution. Thank you
An answer that may be worth it is to add the following line of code:
with
until
you calculate the period of time from one date to another. As parameters it receives the date with which you want to compare and the unit you want as output, I have also added the + 1 that you wanted.An example with your code:
Hope it has fit!
one way to calculate it is also using the Period class as follows...
Period for units greater than or equal to days (days, months, years...).
If you later need to calculate units less than or equal to days (hours, minutes, seconds...) you can use the Duration class.