编程语言
首页 > 编程语言> > JAVA计算两个日期相差月数

JAVA计算两个日期相差月数

作者:互联网

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
java.lang.Math;

	int result = 0;

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	Calendar c1 = Calendar.getInstance();
	Calendar c2 = Calendar.getInstance();

            //起始时间
	c1.setTime(sdf.parse("2012-11-12"));
            //结束时间
	c2.setTime(sdf.parse( "2012-12-12"));

            result = c2.get(Calendar.YEAR)*12 - c1.get(Calendar.YEAR) *12;
            result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH) + result;
            int day = c2.get(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH);
            result = result + (day >= 0 ? 0 : -1);

	return result;

标签:12,相差,get,月数,result,c2,JAVA,Calendar,c1
来源: https://www.cnblogs.com/fpgz99810/p/14742137.html