工具类-4种方式解锁获取两个日期之间的间隔天数
java8的那种方式,没有测试,应该也是可以的。
public class TestDifferentDays {
public static void main(String[] args) {
int differentDays1 = differentDays2(strToDateLong("2020-1-1"), strToDateLong("2019-12-25"));
System.out.println("方式1:" + differentDays1);
String betweenDays = getBetweenDays("2020-1-1", "2019-12-25");
System.out.println("方式2:" + betweenDays);
int differentDays3 = getperiodDays(strToDateLong("2020-1-1"), strToDateLong("2019-12-25"));
System.out.println("方式3:" + differentDays3);
}
/**
* @Desc 获取两个时间之间的间隔天数(方式1)
* @param date1
* @param date2
* @return
*/
public static int differentDays2(Date date1, Date date2) {
if (date1 == null || date2 == null) {
throw new RuntimeException("日期不能为空");
}
LocalDate localDate1 = date2LocalDate(date1);
LocalDate localDate2 = date2LocalDate(date2);
Long until = localDate1.until(localDate2, ChronoUnit.DAYS);
return until.intValue();
// 这种方法是Java8特性
//Generic.long2int(localDate1.until(localDate2, ChronoUnit.DAYS));
}
public static LocalDate date2LocalDate(Date date) {
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDate localDate = instant.atZone(zoneId).toLocalDate();
return localDate;
}
/**
* @Desc 获取两个时间之间的间隔天数(方式2)
* @param startTimeStr
* @param endTimeStr
* @return
*/
public static String getBetweenDays(String startTimeStr, String endTimeStr) {
int betweenDays = 0;
Date startTime = strToDateLong(startTimeStr);
Date endTime = strToDateLong(endTimeStr);
long start = startTime.getTime();
long end = endTime.getTime();
betweenDays = (int) (Math.abs(end - start) / (24 * 3600 * 1000));
return String.valueOf(betweenDays);
}
protected static Date strToDateLong(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 日期相隔天数(方式3)
* @param date1
* @param date2
* @return
*/
public static int getperiodDays(Date date1, Date date2) {
if (date1 == null || date2 == null) {
throw new RuntimeException("日期不能为空");
}
LocalDate localDate1 = date2LocalDate(date1);
LocalDate localDate2 = date2LocalDate(date2);
return periodDays(localDate1, localDate2);
}
public static int periodDays(LocalDate startDateInclusive, LocalDate endDateExclusive) {
return Period.between(startDateInclusive, endDateExclusive).getDays();
}
}