Java计算两个日期间的年,月,日之差
由于在开发中需要计算车的使用年限,我当时使用的是以下方案并记录下来,希望能给有需要计算日期差的朋友有所帮助。当然,中间的计算逻辑根据不同要求来计算。
有错的地方请留言告知
/**
* 计算使用年限
* enrollDate :注册日期
* nowDate : 当前日期或给定日期
*/
public void CalculateTheUseYaers (String enrollDate,String nowDate){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 创建日期格式
Calendar c1 = Calendar.getInstance(); // 创建日历对象
Calendar c2 = Calendar.getInstance();
try {
c1.setTime(sdf.parse(enrollDate));
c2.setTime(sdf.parse(nowDate));
} catch (ParseException e) {
e.printStackTrace();
}
int years = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR); // 计算年度差
int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);// 计算月度差
int day = c2.get(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH);// 计算日数差 (DAY_OF_MONTH为月中的天数)
int months = years *12 + month; // 计算总共相差的月份数
System.out.println("年度差:"+ years);
System.out.println("月度差:" + month);
System.out.println("天数差:" + day);
System.out.println("共相差月份:"+ months);
if (years == 0) { // 同一年
if (months < 11) { // 共相差月份小于11
System.out.println("使用年限为0");
}
if (months == 11) { // 共相差月份等于11
if (day < 0) { // 相差天数小于0
System.out.println("使用年限为0");
}
if (day >= 0) { // 相差天数大于等于0
System.out.println("使用年限为1");
}
}
}
if (years ==1) { // 相差一年
if (months < 11) { // 共相差月份小于11
System.out.println("使用年限为0");
}
if (months == 11) { // 共相差月份等于11
if (day < 0) { // 相差天数小于0
System.out.println("使用年限为0");
}
if (day >= 0) { // 相差天数大于等于0
System.out.println("使用年限为1");
}
}
if (months > 11) {
System.out.println("使用年限为1");
}
}
if (years >=2) { // 相差2年或2年以上
if (month < 0) { // 月度差小于0
System.out.println("使用年限为:"+(years - 1));
}
if (month == 0) { // 月度差等于0
if (day < 0) { // 日数差小于0
System.out.println("使用年限为:"+(years - 1));
}
if (day >= 0) { // 日数差大于等于0
System.out.println("使用年限为:"+ years);
}
}
if (month > 0) { // 月度差大于0
System.out.println("使用年限为:"+ years);
}
}
}