1. 程式人生 > >獲取兩個日期的月份差

獲取兩個日期的月份差

1.需要  joda-time-2.9.9.jar

import org.joda.time.DateTime;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Test {
	
	public static void main(String[] args) {
		
		String startDateStr = "2017-12-18";
		String endDateStr = "2018-10-29";
		
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        DateTime startDate = formatter.parseDateTime(startDateStr);
        DateTime endDate = formatter.parseDateTime(endDateStr);
        int monthNum = Months.monthsBetween(startDate, endDate).getMonths();
        System.out.println(monthNum);
    }

}

 

2.  笨方法取year, month進行計算

package Test;

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

public class Test {
	
	public static void main(String[] args) throws ParseException {
		
		String startDateStr = "2017-12-18";
		String endDateStr = "2018-10-10";
        
        int monthNum = getMonthDiff(startDateStr, endDateStr);
        System.out.println(monthNum);
    }
	
	
	public static int getMonthDiff(String startDateStr, String endDateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date endDate = format.parse(endDateStr);
        Date startDate = format.parse(startDateStr);

        Calendar cEnd = Calendar.getInstance();
        Calendar cStart = Calendar.getInstance();
        cEnd.setTime(endDate);
        cStart.setTime(startDate);
        if (cEnd.getTimeInMillis() < cStart.getTimeInMillis()) return 0;
        int yearEnd = cEnd.get(Calendar.YEAR);
        int yearStart = cStart.get(Calendar.YEAR);
        int monthEnd = cEnd.get(Calendar.MONTH);
        int monthStart = cStart.get(Calendar.MONTH);
        int endDayInt = cEnd.get(Calendar.DAY_OF_MONTH);
        int startDayInt = cStart.get(Calendar.DAY_OF_MONTH);        // 獲取年的差值 假設 d1 = 2015-8-16  d2 = 2011-9-30
        int yearInterval = yearEnd - yearStart;        // 如果 d1的 月-日 小於 d2的 月-日 那麼 yearInterval-- 這樣就得到了相差的年數
        if(monthEnd < monthStart || monthEnd == monthStart && endDayInt < startDayInt) {
            yearInterval --;
        }
//        if(monthEnd < monthStart || monthEnd == monthStart) {
//            yearInterval --;
//        }
        // 獲取月數差值
        int monthInterval = (monthEnd + 12) - monthStart;
        if (endDayInt < startDayInt) {
            monthInterval--;
        }
        monthInterval %= 12;
        int monthNum = yearInterval * 12 + monthInterval;
        return monthNum;
    }

}