计算两个日期之间的月份数(向下取整)

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class ComputeMonth {

    //向下取整
    public static int getMonthDiff(String startDate, String endDate) {
        int result = 0;
        try {
            SimpleDateFormat sfd = new SimpleDateFormat("yyyy/MM/dd");
            Date start = sfd.parse(startDate);
            Date end = sfd.parse(endDate);

            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(start);
            c2.setTime(end);

            int startYear = c1.get(Calendar.YEAR);
            int startMonth = c1.get(Calendar.MONTH);
            int startDay = c1.get(Calendar.DAY_OF_MONTH);
            int endYear = c2.get(Calendar.YEAR);
            int endMonth = c2.get(Calendar.MONTH);
            int endDay = c2.get(Calendar.DAY_OF_MONTH);

            int maxDay = c1.getActualMaximum(Calendar.DAY_OF_MONTH);//获取起始日期所在月的最后一天
            int maxEndDay = c2.getActualMaximum(Calendar.DAY_OF_MONTH);//获取结束日期所在月的最后一天

            if (startDay == maxDay) {//起始日期是在月末
                if (maxEndDay == endDay) {
                    result = (endYear - startYear) * 12 + endMonth - startMonth;
                } else {
                    result = (endYear - startYear) * 12 + endMonth - startMonth - 1;
                }
            } else if (endDay == maxEndDay) {//结束日期是在月末
                result = (endYear - startYear) * 12 + endMonth - startMonth;
            } else {
                if (endDay >= startDay) {
                    result = (endYear - startYear) * 12 + endMonth - startMonth;
                } else {
                    result = (endYear - startYear) * 12 + endMonth - startMonth - 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //支持2019/08/30和2019/-08-30两种格式
    public static int getMonthsByNow(String startDate){
        startDate = startDate.replace("-","/");
        String nowDate = new SimpleDateFormat("yyy/MM/dd").format(new Date());
        int months = 0;
        months = getMonthDiff(startDate,nowDate);//11
        return months;
    }

    public static void main(String[] args) {
        int months = getMonthsByNow("2018/09/17");
        System.out.println(months);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值