1.计算两个日期相差月数,不满一个月按一月算

public class test { public static void main(String[] args) throws Exception { System.out.println(getMonthSpace("2021-09-19","2022-09-09")); } public static int getMonthSpace(String date1, String date2) throws ParseException { int result = 0; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(sdf.parse(date1)); c2.setTime(sdf.parse(date2)); 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; return result == 0 ? 1 : Math.abs(result); }}2.sql语句计算两个日期时间差

select now() 获取当前日期 年月日 时分秒select curdate() 获取当前日期 只有年月日select curtime() 获取当前日期 只有时分秒

计算两个指定日期的月差

SELECT TIMESTAMPDIFF(month,'2020-02-29','2020-04-01') AS DiffDate

计算天的

SELECT DATEDIFF('2008-12-29','2008-12-28') AS DiffDate

来源:

https://blog.csdn.net/YXWik/article/details/109332181