mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
add 添加判断两个日期是否为一周(国内一周的开始为周一,国外一周的开始为周日)
This commit is contained in:
parent
9a88945386
commit
538874562d
@ -348,6 +348,22 @@ public class CalendarUtil {
|
||||
cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA);
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个日期是否为同一周
|
||||
*
|
||||
* @param cal1 日期1
|
||||
* @param cal2 日期2
|
||||
* @return 是否为同一周
|
||||
*/
|
||||
public static boolean isSameWeek(Calendar cal1, Calendar cal2) {
|
||||
if (cal1 == null || cal2 == null) {
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
}
|
||||
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
|
||||
cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
|
||||
cal1.get(Calendar.DAY_OF_WEEK) == cal2.get(Calendar.DAY_OF_WEEK);
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个日期是否为同一月
|
||||
*
|
||||
|
@ -1586,6 +1586,34 @@ public class DateUtil extends CalendarUtil {
|
||||
return CalendarUtil.isSameDay(calendar(date1), calendar(date2));
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个日期是否为同一周
|
||||
*
|
||||
* @param date1 日期1
|
||||
* @param date2 日期2
|
||||
* @param isMon 是否为周一。国内第一天为星期一,国外第一天为星期日
|
||||
* @return 是否为同一周
|
||||
*/
|
||||
public static boolean isSameWeek(final Date date1, final Date date2, boolean isMon) {
|
||||
if (date1 == null || date2 == null) {
|
||||
throw new IllegalArgumentException("The date must not be null");
|
||||
}
|
||||
Calendar calendar1 = calendar(date1);
|
||||
Calendar calendar2 = calendar(date2);
|
||||
if (isMon) {
|
||||
calendar1.setFirstDayOfWeek(Calendar.MONDAY);
|
||||
calendar1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
|
||||
calendar2.setFirstDayOfWeek(Calendar.MONDAY);
|
||||
calendar2.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
|
||||
} else {
|
||||
calendar1.setFirstDayOfWeek(Calendar.SUNDAY);
|
||||
calendar1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
|
||||
calendar2.setFirstDayOfWeek(Calendar.SUNDAY);
|
||||
calendar2.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
|
||||
}
|
||||
return CalendarUtil.isSameWeek(calendar1, calendar2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个日期是否为同一月
|
||||
*
|
||||
|
@ -1004,4 +1004,15 @@ public class DateUtilTest {
|
||||
final DateTime parse = DateUtil.parse("2021-12-01", DatePattern.NORM_DATE_FORMATTER);
|
||||
Assert.assertEquals("2021-12-01 00:00:00", parse.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
// 周六与周日比较
|
||||
final boolean isSameWeek = DateUtil.isSameWeek(DateTime.of("2022-01-01", "yyyy-MM-dd"), DateTime.of("2022-01-02", "yyyy-MM-dd"), true);
|
||||
Assert.assertTrue(isSameWeek);
|
||||
// 周日与周一比较
|
||||
final boolean isSameWeek1 = DateUtil.isSameWeek(DateTime.of("2022-01-02", "yyyy-MM-dd"), DateTime.of("2022-01-03", "yyyy-MM-dd"), false);
|
||||
Assert.assertTrue(isSameWeek1);
|
||||
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user