How to find Start date from time elapsed as percentage and End date in java

103 views Asked by At

i have below code

End date = 31 oct 2024 and
elapsedPercentage is 10% of total duration on current date

as per above params

expected Start date value is 12 aug 2023

but i am getting 07 Dec 2023 from below code

 public static Timestamp calculateStartDate(double elapsedPercentage, Timestamp endDate) {
    try {
        
        LocalDate endDates = endDate.toLocalDateTime().toLocalDate();
        long elapsedDays = (long) (endDates.lengthOfYear() *((100 - elapsedPercentage) / 100.0));
        LocalDate startDate = endDates.minusDays(elapsedDays);
        return  Timestamp.valueOf(startDate.atTime(LocalTime.MIDNIGHT));


    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
2

There are 2 answers

0
Eritrean On BEST ANSWER

Not sure why you are calculating with the lengthOfYear. You should calculate the days between now and end date, which represent (100 - elapsedPercentage)%. You can do that by using DAYS.between() method from java.time.temporal.ChronoUnit. With that you can easily get the number of days to subtract from now to get the start date. Something like:

public static Timestamp calculateStartDate(double elapsedPercentage, Timestamp endDate) {

    LocalDate end    = endDate.toLocalDateTime().toLocalDate();
    LocalDate now    = LocalDate.now();
    long daysBetween = DAYS.between(now, end);
    long toSubtract  = (long) (elapsedPercentage * daysBetween / (100 - elapsedPercentage));
    LocalDate start  = now.minusDays(toSubtract);

    return  Timestamp.valueOf(start.atStartOfDay());
}
6
halil On

With this modification, the code should give you the expected start date of "2023-08-12" when you provide an elapsed percentage of 10% and an end date of "2024-10-31."

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public static Timestamp calculateStartDate(double elapsedPercentage, Timestamp endDate) {
    try {
        // Convert the Timestamp to LocalDateTime
        LocalDateTime endDateTime = endDate.toLocalDateTime();
        
        // Calculate the total duration in days (from end date to one year later)
        long totalDurationDays = ChronoUnit.DAYS.between(endDateTime.toLocalDate(), endDateTime.plusYears(1).toLocalDate());
        
        // Calculate the elapsed days based on the percentage
        long elapsedDays = (long) (totalDurationDays * (elapsedPercentage / 100.0));
        
        // Subtract the elapsed days from the end date
        LocalDate startDate = endDateTime.toLocalDate().minusDays(elapsedDays);
        
        // Create a Timestamp from the start date at midnight
        return Timestamp.valueOf(startDate.atTime(LocalTime.MIDNIGHT));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}