Java比較時間相差幾個月__Java

來源:互聯網
上載者:User
Java比較時間相差幾個月


今天做項目遇到返回距離當前月份6個月的資料


方案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);    }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.