问题:java日期与cron表达式互转工具类
代码如下
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author Guixing
* @Date 2019/3/20 11:19
* @Description
*/
public class DateUtil {
private static final String DATEFORMAT = "ss mm HH dd MM ? yyyy";
/***
*
* @param date
* @param dateFormat : e.g:yyyy-MM-dd HH:mm:ss
* @return
*/
public static String formatDateByPattern(Date date, String dateFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
String formatTimeStr = null;
if (date != null) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
}
/**
* @param cron
* @param dateFormat
* @return
* @throws ParseException
*/
public static Date parseStringToDate(String cron, String dateFormat) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date date = null;
if (cron != null) {
date = sdf.parse(cron);
}
return date;
}
/***
* convert Date to cron ,eg. "0 06 10 15 1 ? 2014"
* @param date : 时间点
* @return
*/
public static String getCron(Date date) {
return formatDateByPattern(date, DATEFORMAT);
}
/***
* convert cron to Date
* @param cron : cron表达式 cron表达式仅限于周为*
* @return
*/
public static Date getDate(String cron) throws ParseException {
return parseStringToDate(cron, DATEFORMAT);
}
}
cron表达式对照表
Field Name Mandatory Allowed Values Allowed Special Characters
Seconds | YES | 0-59 | , - * / |
Minutes | YES | 0-59 | , - * / |
Hours | YES | 0-23 | , - * / |
Day of month | YES | 1-31 | , - * ? / L W |
Month | YES | 1-12 or JAN-DEC | , - * / |
Day of week | YES | 1-7 or SUN-SAT | , - * ? / L # |
Year | NO | empty, 1970-2099 | , - * / |
表1、cron表达式特殊字符意义示意表
特殊字符 |
意义 |
* |
匹配所有的值。如:*在分钟的字段域里表示 每分钟 |
? |
只在日期域和星期域中使用。它被用来指定“非明确的值” |
- |
指定一个范围。如:“10-12”在小时域意味着“10点、11点、12点” |
, |
指定几个可选值。如:“MON,WED,FRI”在星期域里表示“星期一、星期三、星期五” |
/ |
指定增量。如:“0/15”在秒域意思是没分钟的0,15,30和45秒。“5/15”在分钟域表示没小时的5,20,35和50。符号“*”在“/”前面(如:*/10)等价于0在“/”前面(如:0/10) |
L |
表示day-of-month和day-of-week域,但在两个字段中的意思不同,例如day-of-month域中表示一个月的最后一天。如果在day-of-week域表示‘7’或者‘SAT’,如果在day-of-week域中前面加上数字,它表示一个月的最后几天,例如‘6L’就表示一个月的最后一个星期五 |
W |
只允许日期域出现。这个字符用于指定日期的最近工作日。例如:如果你在日期域中写 “15W”,表示:这个月15号最近的工作日。所以,如果15号是周六,则任务会在14号触发。如果15好是周日,则任务会在周一也就是16号触发。如果是在日期域填写“1W”即使1号是周六,那么任务也只会在下周一,也就是3号触发,“W”字符指定的最近工作日是不能够跨月份的。字符“W”只能配合一个单独的数值使用,不能够是一个数字段,如:1-15W是错误的 |
LW |
L和W可以在日期域中联合使用,LW表示这个月最后一周的工作日 |
# |
只允许在星期域中出现。这个字符用于指定本月的某某天。例如:“6#3”表示本月第三周的星期五(6表示星期五,3表示第三周)。“2#1”表示本月第一周的星期一。“4#5”表示第五周的星期三 |
C |
允许在日期域和星期域出现。这个字符依靠一个指定的“日历”。也就是说这个表达式的值依赖于相关的“日历”的计算结果,如果没有“日历”关联,则等价于所有包含的“日历”。如:日期域是“5C”表示关联“日历”中第一天,或者这个月开始的第一天的后5天。星期域是“1C”表示关联“日历”中第一天,或者星期的第一天的后1天,也就是周日的后一天(周一) |
表2、 Cron 表达式特殊字符意义对应表
字段 |
允许值 |
允许的特殊字符 |
秒 |
0-59 |
, - * / |
分 |
0-59 |
, - * / |
小时 |
0-23 |
, - * / |
月内日期 |
1-31 |
, - * ? / L W C |
月 |
1-12 或者 JAN-DEC |
, - * / |
周内日期 |
1-7 或者 SUN-SAT |
, - * ? / L C # |
年(可选) |
留空, 1970-2099 |
, - * / |
更多信息可关注我的公众号 Java知识星球,不定时推送更多原创技术知识文章。