Java获取指定日期到当前日期的差距
一、指定日期到今天的y年m月d日
private JSONObject getYesrMonthDay(String dataParam){
JSONObject res = new JSONObject();
/*只比较年月日,不要时间*/
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate destoryData = LocalDate.parse(dataParam, df);
Date date =new Date();
LocalDate currentData = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// 计算日期差距
Period period = Period.between(destoryData, currentData);
// 获取相差的年、天
Integer years = period.getYears();
Integer days = period.getDays();
Integer mouths = period.getMonths();
res.put("years",years);
res.put("mouths",mouths);
res.put("days",days);
return res;
}
二、指定日期到今天的总日或月数
private Long getDays(String dataParam){
/*只比较年月日,不要时间*/
dataParam = dataParam.substring(0,10);
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate destoryData = LocalDate.parse(dataParam, df);
// 获取今天日期
LocalDate today = LocalDate.now();
// 计算两个日期之间的天数
long daysBetween = ChronoUnit.DAYS.between(destoryData, today);
// 计算相差的月份
long monthsBetween = ChronoUnit.MONTHS.between(specifiedDate, currentDate);
return daysBetween;
}