Java比较时间相差几个月

来源:互联网 发布:windows网络编程 视频 编辑:程序博客网 时间:2024/05/20 14:44

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


阅读全文
0 0
原创粉丝点击