Java计算日期之间相差时间和解决浮点类型精度过长

计算日期之间相差

此处相差计算以分钟为单位,自行可根据业务场景更改

    /**
     * 测试时间相差分钟
     */
    @Test
    public void  getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        simpleDateFormat.applyPattern(DateUtils.NOW_H);

//        加减时间 单位(分钟)
        long time2 = 30 * 60 * 1000; //30 分钟

//        当前时间
        String format = simpleDateFormat.format(new Date().getTime()+time2);

        String oldFormat = "2021-12-18 9:31";

        try {
            long time = simpleDateFormat.parse(format).getTime();

            long oldTime = simpleDateFormat.parse(oldFormat).getTime();
//          相差时间 单位:(分钟)
            int m = (int) ((time-oldTime)/(1000*60));
            System.out.println("==================="+m);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

解决浮点型精度过长

注意:此处的精度保留小数点后两位,浮点过长的浮点类型必须是包装类,否则无效

    /**
     * 测试金额精度过长
     */
    @Test
    public void  getMoney() {
        Double awardMoney = 23.12587994587887;
        Float awardMoney2 = 23.12587994587887F;
        awardMoney = Math.round(awardMoney * 100 ) / 100D;
        awardMoney2 = Math.round(awardMoney2 * 100 ) / 100F;
        System.out.println("Double"+awardMoney);
        System.out.println("Float"+awardMoney2);
    }

 

posted @ 2021-12-20 10:28  阿尔法哲  阅读(262)  评论(0编辑  收藏  举报