java 获取两个日期天数
时间: 2024-05-25 13:06:05 浏览: 89
可以使用Java中的Date类和Calendar类来获取两个日期之间的天数。具体实现方法如下:
```java
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
/**
* 获取两个日期之间的天数
* @param startDate 开始日期
* @param endDate 结束日期
* @return 两个日期之间的天数
*/
public static int getDaysBetween(Date startDate, Date endDate) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
//确保startCalendar在endCalendar之前
if (startCalendar.after(endCalendar)) {
Calendar temp = startCalendar;
startCalendar = endCalendar;
endCalendar = temp;
}
int days = endCalendar.get(Calendar.DAY_OF_YEAR) - startCalendar.get(Calendar.DAY_OF_YEAR);
int endYear = endCalendar.get(Calendar.YEAR);
if (startCalendar.get(Calendar.YEAR) != endYear) {
startCalendar = (Calendar) startCalendar.clone();
do {
days += startCalendar.getActualMaximum(Calendar.DAY_OF_YEAR);
startCalendar.add(Calendar.YEAR, 1);
} while (startCalendar.get(Calendar.YEAR) != endYear);
}
return days;
}
}
```
阅读全文