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;
}