1. 程式人生 > >Java比較時間相差幾個月

Java比較時間相差幾個月

方案1::java1.8新特性YearMonth的compareto方法

同一年進行比較,如當前是2017年8月,傳入引數2017,2,列印:6

但非同一年進行比較,如傳入引數2016,2,期望列印:18,但是實際列印為:1

於是繼續測試,傳入引數2015,2,期望列印:30,但是實際列印為:2

可見 YearMonth的compareto方法當是同一年時返回值為相差幾月,當非同一年時返回相差幾年,並非當前需要的方法。

    /**
     * 利用YearMonth方法compareTo比較兩個時間相差幾月
     * @param year 年
     * @param month 月
     */
    public void testYearMonth(int year, int month) {
        YearMonth yearMonth = YearMonth.of(year, month);
        //當前年月
        YearMonth yearMonthNow = YearMonth.now();
        int difference = yearMonthNow.compareTo(yearMonth);
        System.out.println(difference);
    }

方案2:利用Calender先比較年,再比較月,將相差的幾年乘以12加上相差的月份便的總月份,解決!

    /**
     * 比較時間與當前時間距離幾個月
     *
     * @param dateStr 傳入時間字串,格式yyyyMMddHHmmss
     * @return
     */
    private int compareWithNow(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String afferentYearMonth = DateUtil.getStringSim(dateStr, "yyyyMMddHHmmss", "yyyy-MM");
        String nowYearMonth = YearMonth.now().toString();
        Calendar afferent = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        try {
            afferent.setTime(sdf.parse(afferentYearMonth));
            now.setTime(sdf.parse(nowYearMonth));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int year = (now.get(Calendar.YEAR) - afferent.get(Calendar.YEAR)) * 12;
        int month = now.get(Calendar.MONTH) - afferent.get(Calendar.MONTH);
        return Math.abs(year + month);
    }

原文地址:https://blog.csdn.net/Waria/article/details/77578637