1.获取两个日期时间差
查看支持的时间单位 ChronoUnit类
获取两个LocalDate的时间差
/**
* 入住日期
*/
private LocalDate checkinDate;
/**
* 离店日期
*/
private LocalDate checkoutDate;
long days = ChronoUnit.DAYS.between(checkinDate, checkoutDate);
LocalDateTime a = LocalDateTime.MAX;
LocalDateTime b = LocalDateTime.MIN;
long days1 = ChronoUnit.DAYS.between(a,b);
其他的同理 更换ChronoUnit单位即可
2.时间转字符串
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate.toString());//2019-04-30
System.out.println(DATE_FORMATTER.format(localDate));//2019-04-30
System.out.println(DATETIME_FORMATTER.format(localDateTime));//2019-04-30 16:29:40
}
3.与Date互转
/**
* LocalDate类型转Date类型
*
* @param localDate
* @return Date
*/
public static Date localDateToDate(LocalDate localDate) {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
return Date.from(zdt.toInstant());
}
/**
* LocalDate类型转Date类型
*
* @param localDateTime
* @return Date
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());
}
4.一些补充
/**
* 获得某天最大时间 2017-10-15 23:59:59 的 毫秒数
* @return
*/
static long getMillsOfEndOfDay(LocalDate localDate) {
return localDate.atStartOfDay().with(LocalTime.MAX).toInstant(ZoneOffset.of("+8")).toEpochMilli();
}