如何在java中从经过的时间中找到开始日期和结束日期的百分比

wfsdck30  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(130)

下面有代码
结束日期= 2024年10月31日和
elapsedPercentage是当前日期总持续时间的10%
根据上述参数
预期开始日期值为2023年8月12日
但我得到07十二月2023从下面的代码

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;
    }
}
zi8p0yeb

zi8p0yeb1#

不知道为什么要用lengthOfYear计算。您应该计算从现在到结束日期之间的天数,表示为(100 - elapsedPercentage)%。您可以通过使用java.time.temporal.ChronoUnit中的DAYS.between()方法来实现这一点。有了它,你可以很容易地得到从现在开始减去的天数,以获得开始日期。例如:

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());
}
blpfk2vs

blpfk2vs2#

通过这种修改,当您提供10%的经过百分比和“2024-10-31”的结束日期时,代码应该为您提供“2023-08-12”的预期开始日期。

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;
    }
}

相关问题