CronDateUtils.java
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package cn.com.glsx.entmicro.util;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author zhouhaibao
* @version 1.0
* @description: 时间转cron表达式
* @date 2021/11/11 17:42
*/
@Slf4j
public class CronDateUtils {
private static final String CRON_DATE_FORMAT = "ss mm HH dd MM ?";
private static final String cronTip = " ";
private static final int daysOffset = 30;
private static final int monthOffset = 1;
/***
*
* @param date 时间
* @return cron类型的日期
*/
public static String getCron(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(CRON_DATE_FORMAT);
String formatTimeStr = "";
if (date != null) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
}
/***
*
* @param date 时间
* @return cron类型的日期
*/
public static String getCronByOneMonth(Date date) {
String cron = getCron(date);
log.info("get cron byOneMonth date:{}, cron:{}", DateFormatUtil.toString(date, DateFormatUtil.pattern19), cron);
Date nextDate = DateUtil.offsetMonth(date, monthOffset);
Integer nextMonth = Integer.parseInt(DateFormatUtil.toString(nextDate, "MM"));
Integer nextDays = Integer.parseInt(DateFormatUtil.toString(nextDate, "dd"));
// "18 58 23 11 12,1 ?"
String[] cronArray = cron.split(cronTip);
int days = Integer.parseInt(cronArray[3]);
int month = Integer.parseInt(cronArray[4]);
if (nextDays!=days) {
cronArray[3] = days + "," + nextDays;
}
if (nextMonth!=month) {
cronArray[4] = month + "," + nextMonth;
}
// 生成新的cron表达式
StringBuilder cronSb = new StringBuilder();
for (String cronItem:cronArray) {
cronSb.append(cronItem).append(cronTip);
}
String newCron = cronSb.toString().trim();
log.info("get cron byOneMonth date:{}, newCron:{}", DateFormatUtil.toString(date, DateFormatUtil.pattern19), newCron);
return newCron;
}
public static void main(String[] args) {
String cron = getCronByOneMonth(new Date());
System.out.println(cron);
Date currentDate = DateFormatUtil.toDate("2021-02-28 10:00:02", DateFormatUtil.pattern19);
System.out.println(DateFormatUtil.toString(DateUtil.offsetMonth(currentDate, 1), DateFormatUtil.pattern19));
}
}