如何计算两个时间相差多少周年

1.通过字符串生成日历实体;

 public static Calendar getCalendarFromString(String dateStr, String dateFormatType) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormatType);
        Calendar calendar = null;
        try {
            Date date = sdf.parse(dateStr);
            calendar = Calendar.getInstance();
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return calendar;
    }

2.通过日历实体获取年月日,然后做比较

/**
     * 获取年份间隔,匹配到日,可以进一步扩展到时分秒
     *
     * @param startDate 开始时间
     * @param endDate   结束事件
     * @return 间隔年份
     */
    public static int getYearSpace(String startDate, String endDate) {
        String dateType = "yyyy-MM-dd ";
        Calendar calendar1 = DateUtil.getCalendarFromString(startDate, dateType);
        Calendar calendar2 = DateUtil.getCalendarFromString(endDate, dateType);
        if (calendar1 == null || calendar2 == null) {
            return 0;
        }
        if (calendar1.getTimeInMillis() > calendar2.getTimeInMillis()) {
            Calendar calendar = calendar1;//修正开始时间大于结束时间
            calendar1 = calendar2;
            calendar2 = calendar;
        }
        int year1 = calendar1.get(Calendar.YEAR);
        int month1 = calendar1.get(Calendar.MONTH) + 1;
        int date1 = calendar1.get(Calendar.DATE);
        int year2 = calendar2.get(Calendar.YEAR);
        int month2 = calendar2.get(Calendar.MONTH) + 1;
        int date2 = calendar2.get(Calendar.DATE);
        int years = year2 - year1;
        if (year1 != year2) {
            if (month1 != month2) {
                if (month1 > month2) {
                    years = years - 1;//修正如:2016-8到2017-4    未满一年
                }
            } else {
                if (date1 != date2) {
                    if (date1 > date2) {
                        years = years - 1; //修正如:2016-8-18到2017-8-10  未满一年
                    }
                }
            }
        }
        return years;
    }


你可能感兴趣的:(如何计算两个时间相差多少周年)