获取前(后)x月的日期
package com.jesims.busresume.web; import org.springframework.stereotype.Service; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; @Service public class RiskControlRulesDateUtils { private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); /** * 获取前x月的日期 * @param month * @return */ public Map<String,String> getNowAndBefore(int month){ Date now = new Date(); Date newDate = stepMonth(now, -month); Map<String,String> map =new HashMap<>(); // 现在时间 map.put("now",DATE_FORMAT.format(now)); // 之前时间 map.put("before",DATE_FORMAT.format(newDate)); return map; } /** * 获取后x天的日期 * @param day * @return */ public Map<String,String> getNowAndChangeDay(int day){ Date now = new Date(); Date newDate = stepDay(now, day); Map<String,String> map =new HashMap<>(); // 现在时间 map.put("now",DATE_FORMAT.format(now)); // 之后时间 map.put("change",DATE_FORMAT.format(newDate)); return map; } /** * 在给定的日期加上或减去指定月份后的日期 * @param sourceDate 原始时间 * @param month 要调整的月份,向前为负数,向后为正数 * @return */ public Date stepMonth(Date sourceDate, int month) { Calendar c = Calendar.getInstance(); c.setTime(sourceDate); c.add(Calendar.MONTH, month); return c.getTime(); } /** * 在给定的日期加上或减去指定月份后的日期 * @param * @param day 要调整的天数,向前为负数,向后为正数 * @return */ public Date stepDay(Date sourceDate, int day) { Calendar c = Calendar.getInstance(); c.setTime(sourceDate); c.add(Calendar.DAY_OF_MONTH, day); return c.getTime(); } /** * 输出如下: * "[2016-02, 2016-03, 2016-04, 2016-05, 2016-06, 2016-07, * 2016-08, 2016-09, 2016-10, 2016-11, 2016-12, 2017-01]" */ /** * 获取当前系统时间最近12月的年月(含当月) * @return */ public String[] getLatest12Month(){ String[] latest12Months = new String[12]; Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //要先+1,才能把本月的算进去 for(int i=0; i<12; i++){ cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); //逐次往前推1个月 latest12Months[11-i] = cal.get(Calendar.YEAR)+ "-" +fillZero(cal.get(Calendar.MONTH)+1); } System.out.println(Arrays.toString(latest12Months)); return latest12Months; } public List<String> getLast12Month(){ List<String> list =new ArrayList<>(); String[] latest12Month = getLatest12Month(); for (int i = 0; i < latest12Month.length; i++) { list.add(latest12Month[i]); } for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } return list; } /** * 格式化月份 */ public static String fillZero(int i){ String month = ""; if(i<10){ month = "0" + i; }else{ month = String.valueOf(i); } return month; } }