JAVA 计算两个日期相差月份

代码如下: 

    public static void main(String[] args) throws ParseException{

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str1 = "2014-02-06";
        String str2 = "2012-02-05";
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(sdf.parse(str1));
        aft.setTime(sdf.parse(str2));
        int surplus = aft.get(Calendar.DATE) - bef.get(Calendar.DATE);
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        System.out.println(surplus);
        surplus = surplus <= 0 ? 1 : 0;
        System.out.println(surplus);
        System.out.println("相差月份:" + (Math.abs(month + result) + surplus));

    }

打印结果:

-1
1
相差月份:25

Process finished with exit code 0

参考链接:https://blog.csdn.net/qq_33887333/article/details/72676492


注:因为参考跟我需求不太一样,稍微改了下贴出来了

你可能感兴趣的:(随想)