在此示例中,您将学习如何确定两个定义的日期对象是否在同一天。这意味着我们只对日期信息感兴趣,而忽略这些日期对象的时间信息。在此示例中,我们将使用Apache Commons Lang提供的API。所以这是代码片段:package org.nhooo.example.commons.lang;
import org.apache.commons.lang3.time.DateUtils;
import java.util.Calendar;
import java.util.Date;
public class CheckSameDay {
public static void main(String[] args) {
Date date1 = new Date();
Date date2 = new Date();
// 检查日期是否在同一天。
if (DateUtils.isSameDay(date1, date2)) {
System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
"is on the same day.%n", date1, date2);
}
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// 检查日历是否在同一天。
if (DateUtils.isSameDay(cal1, cal2)) {
System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
"is on the same day.%n", cal1, cal2);
}
cal2.add(Calendar.DAY_OF_MONTH, 10);
if (!DateUtils.isSameDay(cal1, cal2)) {
System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
"is not on the same day.", cal1, cal2);
}
}
}
此代码段产生的示例结果是:24/07/2019 and 24/07/2019 is on the same day.
24/07/2019 and 24/07/2019 is on the same day.
24/07/2019 and 3/08/2019 is not on the same day.
Maven依赖
org.apache.commons
commons-lang3
3.9