说明
今天有个数据处理要将日期格式为yyyy-MM-dd的日期要向前推12个月,我这里记录下这个方法,留着以后需要的时候再用。
代码
方法即可向前推也可向后推月份。
@GetMapping("/test222")
public String test222(HttpServletRequest request){
String date = request.getParameter("date");
String num = request.getParameter("num");
return getBeforeXMonthDate(date,Integer.parseInt(num));
}
//将月粒度日期格式yyyy-MM-dd格式向前推X个月或向后推X个月的方法
public String getBeforeXMonthDate(String date,int month){
Calendar calendar=Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
//将传过来的日期设置给calendar
calendar.setTime(sdf.parse(date));
//System.out.println("当前日期="+sdf.format(calendar.getTime()));
//将传过来的月份减去X个月或者加上X个月
calendar.add(Calendar.MONTH, month);
//System.out.println("向前推12月之前的日期="+sdf.format(calendar.getTime()));
}catch (Exception e){
e.printStackTrace();
}
return sdf.format(calendar.getTime());
}
postman调用该方法后,返回如下:
向前推1一个月日期:
向后推1一个月日期: