修复DateUtil.betweenYear闰年2月问题

This commit is contained in:
Looly
2024-03-12 17:32:55 +08:00
parent f15612cd55
commit 126674a453
4 changed files with 47 additions and 18 deletions

View File

@@ -15,6 +15,7 @@
* 【core 】 修复PathMover对目标已存在且只读文件报错错误问题issue#I95CLT@Gitee
* 【json 】 修复JSONUtil序列化和反序列化预期的结果不一致问题pr#3507@Github
* 【http 】 修复CVE-2022-22885HttpGlobalConfig可选关闭信任hostissue#2042@Github
* 【core 】 修复DateUtil.betweenYear闰年2月问题issue#I97U3J@Gitee
-------------------------------------------------------------------------------------------------------------
# 5.8.26(2024-02-10)

View File

@@ -360,6 +360,17 @@ public class CalendarUtil {
cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA);
}
/**
* 是否为本月最后一天
*
* @param calendar {@link Calendar}
* @return 是否为本月最后一天
* @since 5.8.27
*/
public static boolean isLastDayOfMonth(Calendar calendar) {
return calendar.get(Calendar.DAY_OF_MONTH) == calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 比较两个日期是否为同一周
*

View File

@@ -137,15 +137,20 @@ public class DateBetween implements Serializable {
int result = endCal.get(Calendar.YEAR) - beginCal.get(Calendar.YEAR);
if (false == isReset) {
final int beginMonthBase0 = beginCal.get(Calendar.MONTH);
final int endMonthBase0 = endCal.get(Calendar.MONTH);
if (beginMonthBase0 < endMonthBase0) {
return result;
} else if (beginMonthBase0 > endMonthBase0) {
return result - 1;
} else if (Calendar.FEBRUARY == beginMonthBase0
&& CalendarUtil.isLastDayOfMonth(beginCal)
&& CalendarUtil.isLastDayOfMonth(endCal)) {
// 考虑闰年的2月情况
if (Calendar.FEBRUARY == beginCal.get(Calendar.MONTH) && Calendar.FEBRUARY == endCal.get(Calendar.MONTH)) {
if (beginCal.get(Calendar.DAY_OF_MONTH) == beginCal.getActualMaximum(Calendar.DAY_OF_MONTH)
&& endCal.get(Calendar.DAY_OF_MONTH) == endCal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
// 两个日期都位于2月的最后一天此时月数按照相等对待此时都设置为1号
beginCal.set(Calendar.DAY_OF_MONTH, 1);
endCal.set(Calendar.DAY_OF_MONTH, 1);
}
}
endCal.set(Calendar.YEAR, beginCal.get(Calendar.YEAR));
long between = endCal.getTimeInMillis() - beginCal.getTimeInMillis();

View File

@@ -75,4 +75,16 @@ public class DateBetweenTest {
ChronoUnit.WEEKS);
Assert.assertEquals(betweenWeek, betweenWeek2);
}
@Test
public void issueI97U3JTest(){
String dateStr1 = "2024-02-29 23:59:59";
Date sdate = DateUtil.parse(dateStr1);
String dateStr2 = "2023-03-01 00:00:00";
Date edate = DateUtil.parse(dateStr2);
long result = DateUtil.betweenYear(sdate, edate, false);
Assert.assertEquals(0, result);
}
}