首页 > 解决方案 > Java 时间段(十进制月数)

问题描述

我们可以得到十进制值的两个日期之间的差异。

从日期 - 2021-08-01

迄今为止 - 2021-08-16

差异 - 0.5

逻辑应该支持任何日期。

例如:- 2021-07-12 和 2021-08-5 之间的差异

标签: javadate

解决方案


当您在评论中清除了您的预期价值和业务时,我将用这个替换我的旧答案:

您可以使用LocalDateTime从天数到月份识别等各种操作。即使日期在不同的月份中,以下代码也完全符合您的要求:

public static void main(String[] args) {
    double res = 0;
    LocalDate localDate1 = LocalDate.parse("2021-08-01");
    LocalDate localDate2 = LocalDate.parse("2021-08-16");

    if (localDate1.getMonthValue() == localDate2.getMonthValue()) {
        Period period = Period.between(localDate1, localDate2.plusDays(1));
        long days = period.getDays();
        res = (double) days / localDate1.lengthOfMonth();
    } else {
        int daysLeftInPrevMonth = localDate1.lengthOfMonth() - localDate1.getDayOfMonth();
        int diffOfMonths = localDate2.getMonthValue() - localDate1.getMonthValue() - 1;
        int daysLeftInNextMonth = localDate2.getDayOfMonth();
        res = (double) daysLeftInPrevMonth / localDate1.lengthOfMonth() + diffOfMonths
                + (double) daysLeftInNextMonth / localDate2.lengthOfMonth();

    }

    Double finalResult = BigDecimal.valueOf(res)
            .setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
    System.out.println(finalResult);

}

注意:请记住,第一个日期应小于第二个日期。


推荐阅读