业务需求:定时任务每年12月25日生成下一年的日期
@Component
public class GenerateDateTask {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
TimeMapper timeMapper;
/**
* 每年的12月25日自动生成下一年的日期
*/
@Async
@Scheduled(cron = "0 0 0 25 12 ? ")
public void autoGenerateDate(){
List<String> dates = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//获取下一年
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR,1);
//设置下一年的开始和结束日期
String startDate = calendar.get(Calendar.YEAR)+"-01-01";
String endDate = calendar.get(Calendar.YEAR)+"-12-31";
try {
Date startDate2 = sdf.parse(startDate);
Date endDate2 = sdf.parse(endDate);
dates.add(startDate);
Calendar calStart = Calendar.getInstance();
calStart.setTime(startDate2);
//循环出日期存在list
while(endDate2.after(calStart.getTime())){
calStart.add(Calendar.DAY_OF_MONTH,1);
dates.add(sdf.format(calStart.getTime()));
}
} catch (ParseException e) {
e.printStackTrace();
}
//插入t_time表
if(dates.size()>0){
timeMapper.insertDate(dates);
}
}
}
方式二:
public static List<String> AutoGenerateDate(){
List<String> dates = new ArrayList<>();
//获取日期对象,默认是当前时间
Calendar calendar = Calendar.getInstance();
//加一年,获取下一年
calendar.add(Calendar.YEAR,1);
int year = calendar.get(Calendar.YEAR);
//设置下一年的开始日期和结束日期
String dateStart=year+"-01-01";
String dateEnd=year+"-12-31";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
long startTime = sdf.parse(dateStart).getTime();
long endTime = sdf.parse(dateEnd).getTime();
long day = 1000*60*60*24;
//将日期存到list
for(long i = startTime;i<=endTime;i+=day){
dates.add(sdf.format(new Date(i)));
}
return dates;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}