代碼如下:
public static void main(String[] args) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str1 = "2014-02-06";
String str2 = "2012-02-05";
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 ? 1 : 0;
}else{
result = 0;
}
System.out.println(result);
System.out.println("相差年份:" + ((Math.abs(year)) + result));
}
運行結果:
0
1
相差年份:3
Process finished with exit code 0