Java 计算两个日期相减并转换成月份

Java 计算两个日期相减并转换成月份

在网上找了很多类似方法结果都是垃圾,于是乎记录下来给需要的人
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
 
public class MonthTest{
 
    public static void main(String[] args) throws ParseException {
        String d1 = "2012-01-12";
        String d2 = "2010-02-11";
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(sdf.parse(d1));
        int year1 = c.get(Calendar.YEAR);
        int month1 = c.get(Calendar.MONTH);
         
        c.setTime(sdf.parse(d2));
        int year2 = c.get(Calendar.YEAR);
        int month2 = c.get(Calendar.MONTH);
         
        int result;
        if(year1 == year2) {
            result = month1 - month2;
        } else {
            result = 12*(year1 - year2) + month1 - month2;
        }
        System.out.println(result);
    }
}

你可能感兴趣的:(java,计算两个日期相减并转换成月份)