mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
修复DateUtil.betweenYear闰年2月问题
This commit is contained in:
@@ -15,6 +15,7 @@
|
||||
* 【core 】 修复PathMover对目标已存在且只读文件报错错误问题(issue#I95CLT@Gitee)
|
||||
* 【json 】 修复JSONUtil序列化和反序列化预期的结果不一致问题(pr#3507@Github)
|
||||
* 【http 】 修复CVE-2022-22885,HttpGlobalConfig可选关闭信任host(issue#2042@Github)
|
||||
* 【core 】 修复DateUtil.betweenYear闰年2月问题(issue#I97U3J@Gitee)
|
||||
|
||||
-------------------------------------------------------------------------------------------------------------
|
||||
# 5.8.26(2024-02-10)
|
||||
|
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个日期是否为同一周
|
||||
*
|
||||
|
@@ -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();
|
||||
|
@@ -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);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user