Java计算两个日期间的年,月,日之差
2017-06-17 10:13
323 查看
由于在开发中需要计算车的使用年限,我当时使用的是以下方案并记录下来,希望能给有需要计算日期差的朋友有所帮助。当然,中间的计算逻辑根据不同要求来计算。
有错的地方请留言告知
有错的地方请留言告知
/** * 计算使用年限 * 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); } } }
相关文章推荐
- java 计算生日 剩余天数 (两个日期间隔天数)
- Java 计算两个日期的时间差
- java中计算两个日期相差几天
- [Java] 计算两个日期之间的差(年 月 日)
- java中计算两个日期相差几天
- java 输入日期取星期几的方法 计算两个时间段中间的
- [Java] 计算两个日期之间的差(年 月 日)
- [Java] 计算两个日期之间的差(年 月 日)
- Java中计算两个日期相差几天
- java实现计算两个日期相差多少月、比较两个日期大小 等常用日期操作
- 【原创工具】JAVA后台计算两个日期之间的工作日时间差
- Java中计算任意两个日期之间的工作天数
- java 计算两个日期之间天数
- Java按自然月计算两个日期相差的年月日
- Java 中计算两个日期差
- JAVA计算两个日期之间的天数
- 计算天数------java两个日期之间的天数、分钟计算
- java 计算两个日期之间天数
- java中计算两个日期之间差的天数
- java实现计算两个日期间间隔天数