代码:
public static Long getDaysBetween(Date startDate, Date endDate) {
Calendar fromCalendar = Calendar.getInstance();
fromCalendar.setTime(startDate);
fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
fromCalendar.set(Calendar.MINUTE, 0);
fromCalendar.set(Calendar.SECOND, 0);
fromCalendar.set(Calendar.MILLISECOND, 0);
Calendar toCalendar = Calendar.getInstance(); // 没必要实例化两个Calendar !!!
toCalendar.setTime(endDate);
toCalendar.set(Calendar.HOUR_OF_DAY, 0);
toCalendar.set(Calendar.MINUTE, 0);
toCalendar.set(Calendar.SECOND, 0);
toCalendar.set(Calendar.MILLISECOND, 0);
return (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
}
public static Long getDaysBetween(Date startDate, Date endDate) {
Calendar calendar = CAL_INSTANCE.get();
calendar.setTime(startDate);
cleanHHmmss(calendar);
long fromTime = calendar.getTime().getTime();
calendar.setTime(endDate);
cleanHHmmss(calendar);
long toTime = calendar.getTime().getTime();
return (fromTime - toTime) / MILLISECONDS_A_DAY;
}
private static final ThreadLocal CAL_INSTANCE = new ThreadLocal() {
@Override
protected Calendar initialValue() {
return Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));
}
};