java 获取两个日期时间间隔

public class DateTest02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LocalDate localDate = LocalDate.now();
	
		LocalDate parse = LocalDate.parse("2011-12-07");
		
		Period between = Period.between(parse,localDate);
		//获取两个日期之间相差多少年
		System.out.println(between.getYears());
		//获取两个日期之间相差多少月
		System.out.println(between.toTotalMonths());
		//获取两个日期之间相差多少天
		System.out.println(localDate.toEpochDay()-parse.toEpochDay());
	}
}

LocalDate与Date类型的相互转换:

1、LocalDate转换成Date

 public static Date localDate2Date(LocalDate localDate) {
        if(null == localDate) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

2.LocalDateTime转换成Date

public static Date localDateTime2Date(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

3.LocalDate格式化

    public static String formatDate(Date date) {
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        return localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

你可能感兴趣的:(java 获取两个日期时间间隔)