1.需求
使用mybatis获取数据时,需要把当前时间减去xx天,来和数据库的表中的时间进行对比
2.解决方法
days
参数是当前时间减去days天
//对时间进行换算
String format_days;
if(days==0){
format_days="0";
}else{
Date d=new Date();
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
format_days=sdf.format(new Date(d.getTime()-days*24l*60l*60l*1000l));
}
主要要点在于
d.getTime()-days*24l*60l*60l*1000l)
对时间的增减,其中数字后面加上l是为了防止乘数过大变成负数(不加l大概减25天以上就会导致乘数的结果变成负数,以至于天数反倒增加)
映射文件中对日期进行对比如下
<if test="days!='0'.toString()">
and publish_time > #{days}
</if>
days实际上是一个字符串,不加toString会导致编译器将其识别为数字或是char字符,发生错误