初始代码
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 < #{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 < #{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)