JAVA 计算两个日期相差年份
直接上代码:
public static void main(String[] args) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str1 = "2012-02-05";
String str2 = "2014-02-06";
Calendar bef = Calendar.getInstance();
Calendar aft = Calendar.getInstance();
bef.setTime(sdf.parse(str1));
aft.setTime(sdf.parse(str2));
int surplus = aft.get(Calendar.DATE) - bef.get(Calendar.DATE);
int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
int year = aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR);
System.out.println(result);
if(result > 0){
result = 1;
}else if(result == 0){
result = surplus <= 0 ? 0 : 1;
}else{
result = 0;
}
System.out.println(result);
System.out.println("相差年份:" + (year + result));
}
运行结果:
0
1
相差年份:3
Process finished with exit code 0