实际项目中经常需要对传入的日期时间进行判断,如是否为一年内,几个月之内,几天前,几天之内等等的需求。如要求前端传入的日期是要为当前日期一年内的某个日期,基于jdk8的LocalDateTime or LocalDate等常用的做法如下:
// 前端传字符串如‘2020-07-13 09:09:09’ springmvc接收并转换为LocalDateTime类型
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime endTime;
LocalDateTime now = LocalDateTime.now();
// jdk8校验传入日期是否为一年内
boolean flag = endTime.isBefore(now.plusYears(1))
基于上述的做法通常是比较通用的模式,如果每个日期时间都重复如此判断,略微繁琐,于是可以通过javax.validation的自定义校验注解来作用于实体属性上,借住hibernate-validate与springmvc结合来解决此类日期时间的范围校验。
/**
* 日期时间范围校验注解,可作用于LocalDateTime or 字符串型年月日时分秒(格式可通过pattern属性指定)
*
* @author meilin.huang
* @date 2020-07-09 1:51 下午
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = DateTimeRange.DateTimeRangeValidator.class)
public @interface DateTimeRange {
/**
* 最小时间范围(为负数即为前n unit)
*/
int min() default 0;
int max() default Integer.MAX_VALUE;
/**
* 时间单位 (年月日)
*/
RangeUnit unit() default RangeUnit.DAYS;
/**
* 作用于字符串时,指定的格式,包含年月日时分秒
*/
String pattern() default "yyyy-MM-dd HH:mm:ss";
/**
* 是否忽略更小的单位,即比当前指定的unit更小的单位(如unit为Days,则忽略hours,minutes, second)
*/
boolean ignoreLowerUnit() default false;
/**
* 错误提示
*/
String message() default "日期时间错误";
/**
* 用于分组校验
*/
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
class DateTimeRangeValidator implements ConstraintValidator {
private DateTimeRange dateTimeRange;
@Override
public void initialize(DateTimeRange dateRange) {
this.dateTimeRange = dateRange;
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
LocalDateTime ta = getByValue(value);
if (ta == null) {
return false;
}
RangeUnit unit = dateTimeRange.unit();
int min = dateTimeRange.min();
int max = dateTimeRange.max();
// 忽略更小单位时,计算两个时间的单位差值比较即可
if (dateTimeRange.ignoreLowerUnit()) {
long between = RangeUnit.getBetween(dateTimeRange.unit(), LocalDateTime.now(), ta);
return between >= min && between <= max;
}
LocalDateTime now = LocalDateTime.now();
return ta.isAfter((ChronoLocalDateTime>) RangeUnit.plus(now, unit, min))
&& ta.isBefore((ChronoLocalDateTime>) RangeUnit.plus(now, unit, max));
}
private LocalDateTime getByValue(Object value) {
if (value instanceof LocalDateTime) {
return (LocalDateTime) value;
}
if (value instanceof String) {
try {
return LocalDateTime.parse((String) value, DateTimeFormatter.ofPattern(dateTimeRange.pattern()));
} catch (Exception e) {
return null;
}
}
return null;
}
}
}
/**
* 日期范围校验,作用于 {@link LocalDate} or 字符串(年月日,格式可通过pattern属性指定,默认格式为: yyyy-MM-dd)
*
* @author meilin.huang
* @date 2020-07-08 5:15 下午
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = DateRange.DateRangeValidator.class)
public @interface DateRange {
/**
* 最小时间范围(为负数即为前n unit)
*/
int min() default 0;
int max() default Integer.MAX_VALUE;
/**
* 时间单位 (年月日)
*/
RangeUnit unit() default RangeUnit.DAYS;
/**
* 作用于字符串时,指定的格式,只能包含年月日不包含时间
*/
String pattern() default "yyyy-MM-dd";
/**
* 是否忽略更小的单位,即比当前指定的unit更小的单位(如unit为Month,则忽略Days)
*/
boolean ignoreLowerUnit() default false;
/**
* 错误提示
*/
String message() default "日期错误";
/**
* 用于分组校验
*/
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
class DateRangeValidator implements ConstraintValidator {
private DateRange dateRange;
@Override
public void initialize(DateRange dateRange) {
this.dateRange = dateRange;
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
LocalDate ta = getByValue(value);
if (ta == null) {
return false;
}
// 忽略更小单位时,计算两个时间的单位差值比较即可
if (dateRange.ignoreLowerUnit()) {
long between = RangeUnit.getBetween(dateRange.unit(), LocalDate.now(), ta);
return between >= dateRange.min() && between <= dateRange.max();
}
LocalDate now = LocalDate.now();
RangeUnit unit = dateRange.unit();
ChronoLocalDate min = (ChronoLocalDate) RangeUnit.plus(now, unit, dateRange.min());
ChronoLocalDate max = (ChronoLocalDate) RangeUnit.plus(now, unit, dateRange.max());
return (ta.isAfter(min) || ta.isEqual(min))
&& (ta.isBefore(max) || ta.isEqual(max));
}
private LocalDate getByValue(Object value) {
if (value instanceof LocalDate) {
return (LocalDate) value;
}
if (value instanceof String) {
try {
return LocalDate.parse((String) value, DateTimeFormatter.ofPattern(dateRange.pattern()));
} catch (Exception e) {
return null;
}
}
if (value instanceof LocalDateTime) {
return ((LocalDateTime) value).toLocalDate();
}
return null;
}
}
}
/**
* @author meilin.huang
* @date 2020-07-09 2:06 下午
*/
public enum RangeUnit {
/**
* 年
*/
YEAR,
MONTH,
DAYS,
WEEKS,
HOURS,
MINUTES,
SECOND;
public static Temporal plus(Temporal date, RangeUnit unit, long value) {
switch (unit) {
case DAYS:
return date.plus(value, ChronoUnit.DAYS);
case MONTH:
return date.plus(value, ChronoUnit.MONTHS);
case YEAR:
return date.plus(value, ChronoUnit.YEARS);
case WEEKS:
return date.plus(value, ChronoUnit.WEEKS);
case HOURS:
return date.plus(value, ChronoUnit.HOURS);
case MINUTES:
return date.plus(value, ChronoUnit.MINUTES);
case SECOND:
return date.plus(value, ChronoUnit.SECONDS);
default:
return date;
}
}
public static long getBetween(RangeUnit unit, Temporal date, Temporal date2) {
switch (unit) {
case DAYS:
return ChronoUnit.DAYS.between(date, date2);
case MONTH:
return ChronoUnit.MONTHS.between(date, date2);
case YEAR:
return ChronoUnit.YEARS.between(date, date2);
case WEEKS:
return ChronoUnit.WEEKS.between(date, date2);
case HOURS:
return ChronoUnit.HOURS.between(date, date2);
case MINUTES:
return ChronoUnit.MINUTES.between(date, date2);
case SECOND:
return ChronoUnit.SECONDS.between(date, date2);
default:
return 0;
}
}
}
public class ValidatorUtilsTest extends TestCase {
public static class User {
/**
* createTime必须在当前日期的前一个月以及后一个月访问内,忽略day的比较
* 即计算当前时间与传入createTime的月份差是否在最小与最大值范围内
*/
@DateRange(min = -1, max = 1, unit = RangeUnit.MONTH, ignoreLowerUnit = true, message = "createTime范围错误")
String createTime = "2020-06-09";
/**
* date必须为当前日期时间的后一个月至后两月内
*/
@DateTimeRange(min = 1, max = 2, unit = RangeUnit.MONTH, message = "date范围错误")
String date = "2020-08-15 09:18:00";
@DateTimeRange(min = 10, max = 30, message = "endTime日期范围错误")
LocalDateTime endTime = LocalDateTime.now().plusDays(30);
}
@Test
public void testValidate() {
ValidationResult validate = ValidatorUtils.validate(new User());
System.out.println(validate);
}
}
通过注解的方式对参数的日期时间属性进行范围校验,可以简化代码,去除冗余重复繁琐的代码,舒服不是一点点。当然以上是基于jdk8的localdatetime和localdate实现,如需要对Date
类型范围校验,稍作修改即可。更多方便有趣的代码可以前往个人业余总结以及练手项目中获取哈https://gitee.com/objs/mayfly