最近工作中遇到要查询数据中最近5个月中每月最后一天的数据,先写了个工具类,调用工具类把最近5各月最后一天的数据添加到List里,sql中用foreach标签遍历该List,遍历的sql如下:
<foreach item="value" collection="netDateList" open="(" separator="," close=")">
#{value}
</foreach>
其中netDateList是后台穿过来的List
。工具类代码如下:
运行结果如下:
2014-04-30
2014-03-31
2014-02-28
2014-01-31
2013-12-31
<foreach item="value" collection="netDateList" open="(" separator="," close=")">
#{value}
</foreach>
其中netDateList是后台穿过来的List
。工具类代码如下:
public class GetLastDateOfMonthUtil {
/**
*
* @param n 代表查询的最近n月
* @return
*/
public static Date getLastDayOfMonth(int n) {
Calendar cal = Calendar.getInstance();
Calendar l = (Calendar) cal.clone();
l.clear();
l.set(Calendar.YEAR, cal.get(Calendar.YEAR));
l.set(Calendar.MONTH, cal.get(Calendar.MONTH)-n);
l.set(Calendar.MILLISECOND, -1);
return l.getTime();
}
public static void main(String[] args) {
//测试查询最近5个月
for(int i=0;i<5;i++){
Date date = GetLastDateOfMonthUtil.getLastDayOfMonth(i);
String lastday = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(lastday);
}
}
}
运行结果如下:
2014-04-30
2014-03-31
2014-02-28
2014-01-31
2013-12-31