欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

计算两个日期之间相差的月数 博客分类: Java java计算两个日期之间相差的月数 

程序员文章站 2024-03-16 12:16:52
...
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {

	/**
	 * 得到两日期相差几个月
	 * 
	 * @return
	 */
	public static long getMonth(String date1, String date2) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int result = 0;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();

		try {
			c1.setTime(sdf.parse(date1));
			c2.setTime(sdf.parse(date2));
			result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return result == 0 ? 1 : Math.abs(result);
	}
    
    /**
     * 计算两个日期之间相差的月数
     * 
     * @param date1
     * @param date2
     * @return
     */
    public static int getMonth(Date date1, Date date2) {
        int iMonth = 0;
        int flag = 0;
        try {
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);

            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date2);

            if (cal2.equals(cal1)) return 0;
            if (cal1.after(cal2)) {
                Calendar temp = cal1;
                cal1 = cal2;
                cal2 = temp;
            }
            if (cal2.get(Calendar.DAY_OF_MONTH) < cal1.get(Calendar.DAY_OF_MONTH)) flag = 1;

            if (cal2.get(Calendar.YEAR) > cal1.get(Calendar.YEAR))
                iMonth = ((cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR)) * 12 + cal2.get(Calendar.MONTH) - flag)
                         - cal1.get(Calendar.MONTH);
            else iMonth = cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH) - flag;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return iMonth;
    }

}