我们可以用十进制值获取两个日期之间的差异吗。
从日期 - 2021-08-01
迄今为止 - 2021-08-16
差异 - 0.5
逻辑应该支持任何日期。
例如:- 2021-07-12和2021-08-5的区别
我们可以用十进制值获取两个日期之间的差异吗。
从日期 - 2021-08-01
迄今为止 - 2021-08-16
差异 - 0.5
逻辑应该支持任何日期。
例如:- 2021-07-12和2021-08-5的区别
当您在评论中清除了您的预期价值和业务时,我将用这个替换我的旧答案:
您可以使用 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);
}
注意:请记住,第一个日期应小于第二个日期。