java 7 比较两个date是不是同一天 相差几天
时间: 2023-12-06 13:05:02 浏览: 91
Java判断两个日期相差天数的方法
可以使用Java 7中的Calendar类来比较两个Date是否为同一天,以及计算它们之间相差的天数。
比较两个Date是否为同一天:
```java
public static boolean isSameDay(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
&& cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)
&& cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
}
```
计算两个Date之间相差的天数:
```java
public static int daysBetween(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.set(Calendar.MILLISECOND, 0);
cal2.set(Calendar.HOUR_OF_DAY, 0);
cal2.set(Calendar.MINUTE, 0);
cal2.set(Calendar.SECOND, 0);
cal2.set(Calendar.MILLISECOND, 0);
long diff = cal2.getTimeInMillis() - cal1.getTimeInMillis();
return (int) (diff / (24 * 60 * 60 * 1000));
}
```
注意,在计算相差天数时,需要将两个Date的时间部分设置为0,以确保只计算日期的差异。
阅读全文