方案1::java1.8新特性YearMonth的compareto方法
同一年进行比较,如当前是2017年8月,传入参数2017,2,打印:6
但非同一年进行比较,如传入参数2016,2,期望打印:18,但是实际打印为:1
于是继续测试,传入参数2015,2,期望打印:30,但是实际打印为:2
可见 YearMonth的compareto方法当是同一年时返回值为相差几月,当非同一年时返回相差几年,并非当前需要的方法。
/**
* 利用YearMonth方法compareTo比较两个时间相差几月
* @param year 年
* @param month 月
*/
public void testYearMonth(int year, int month) {
YearMonth yearMonth = YearMonth.of(year, month);
//当前年月
YearMonth yearMonthNow = YearMonth.now();
int difference = yearMonthNow.compareTo(yearMonth);
System.out.println(difference);
}
方案2:利用Calender先比较年,再比较月,将相差的几年乘以12加上相差的月份便的总月份,解决!
/**
* 比较时间与当前时间距离几个月
*
* @param dateStr 传入时间字符串,格式yyyyMMddHHmmss
* @return
*/
private int compareWithNow(String dateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
String afferentYearMonth = DateUtil.getStringSim(dateStr, "yyyyMMddHHmmss", "yyyy-MM");
String nowYearMonth = YearMonth.now().toString();
Calendar afferent = Calendar.getInstance();
Calendar now = Calendar.getInstance();
try {
afferent.setTime(sdf.parse(afferentYearMonth));
now.setTime(sdf.parse(nowYearMonth));
} catch (ParseException e) {
e.printStackTrace();
}
int year = (now.get(Calendar.YEAR) - afferent.get(Calendar.YEAR)) * 12;
int month = now.get(Calendar.MONTH) - afferent.get(Calendar.MONTH);
return Math.abs(year + month);
}