public class Test { /** * 日期格式化:yyyy-MM-dd */ public static final String DATE_FORMAT_STR = "yyyy-MM-dd";
/** * 获取两个日期相差多少个月 * @param dateOne 时间1-小的时间 * @param dateTwo 时间2-大的时间 * @return */ public static int getMonthSpace(String dateOne, String dateTwo){ int result = 0; try { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_STR); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(sdf.parse(dateOne)); c2.setTime(sdf.parse(dateTwo)); int i = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR); int month = 0; if (i<0) { month = -i * 12; }else if(i>0) { month = i * 12; } result = (c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH)) + month; } catch (ParseException e) { e.printStackTrace(); } return result == 0 ? 1 : Math.abs(result); } public static void main(String[] args) { //获取系统当前时间 2022-06-28 String systemDate = DateUtil.format(new Date(),DATE_FORMAT_STR);
// 控制台打印结果:6 System.out.println(getMonthSpace( systemDate,"2023-06-28")); } }
标签:两个,String,get,int,result,计算,c2,相差,Calendar From: https://www.cnblogs.com/songweipeng/p/17009379.html