java Date 类型踩坑

初始代码

 Date now = new Date();
 queryCriteria.setSelectYearMonth(DateUtils.parseDate(DateFormatUtils.format(now,"yyyy-MM")));
int reportCounts = machineryReportRepairMapper.getReportCountsByMachineryList(queryCriteria.getProcessId(),
                    queryCriteria.getSelectYearMonth(), queryCriteria.getYearMonthDay());
int getReportCountsByMachineryList(@Param("processId") Long processId, @Param("month") Date yearMonth, @Param("monthDay") String yearMonthDay);
<select id="getReportCountsByMachineryList" resultType="java.lang.Integer">
        select count(repair.id)
        from tpm_machinery_report_repair repair
        left join tpm_machinery_info  info on info.id = repair.machinery_id and info.del_flag = 1
        <where>
            <if test="processId != null ">
                and info.process_id = #{processId}
            </if>
            <if test="month != null">
                and repair.create_time like concat(#{month}, '%')
            </if>
            <if test="monthDay != null and monthDay != ''">
                and repair.create_time &lt; #{monthDay}
            </if>
        </where>
 </select>

运行结果

先将获取的当前Date类型的时间转化为String 类型的格式“yyyy-MM’年月,但是在转化Date类型会发现格式亦然不对,经过大量搜索发现将Date类型转化为标准格式化年月然后在转为Date 标准格式都是丢掉的
在这里插入图片描述

解决方法

 select count(repair.id)
        from tpm_machinery_report_repair repair
        left join tpm_machinery_info  info on info.id = repair.machinery_id and info.del_flag = 1
        <where>
            <if test="processId != null ">
                and info.process_id = #{processId}
            </if>
            <if test="month != null">
                and repair.create_time like concat(date_format(#{month}, '%Y-%m'), '%')
            </if>
            <if test="monthDay != null and monthDay != ''">
                and repair.create_time &lt; #{monthDay}
            </if>
</where>

缺陷

传入的时间类型必须为date类型,不然亦然会转化失效

总结

java Spring boot Date 类型格式化,常用的方法有借用DateFormatUtils或者DateUtils,再或者直接使用

 DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("yyyy-MM") nowDate.format(monthFormatter) 
 //或者
 SimpleDateFormat monthFormatter = DateTimeFormatter.ofPattern("yyyy-MM") nowDate.format(monthFormatter)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值