java - Java 时间段(十进制月数)
问题描述
我们可以得到十进制值的两个日期之间的差异。
从日期 - 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);
}
注意:请记住,第一个日期应小于第二个日期。
推荐阅读
- python - 如何使用请求从互联网上的 json 文件中获取信息
- c# - Docusign“无法加载文件或程序集 Restsharp”错误
- javascript - 为什么在 JavaScript 中对数组“B”的更改会传播到数组“A”(用于定义“B”但此后从未直接修改)?
- css - 如何在悬停时使顶部弹性框行不向下推底部弹性框行
- php - 预订系统的 PHP 对象/数组算法
- python - Django rest 框架简单模型序列化器列表视图需要永远显示 10 条记录
- apache-nifi - 如何在 Apache NIFI 中将机器学习应用于流数据
- regex - Notepad++ 正则表达式 - 如何从此列表中删除代理?
- sas - 将Stata“egen,group”转换为SAS
- kubernetes - kubernetes 容器中的 redis-cluster 在 spinup 时重新启动