實際項目中經常需要對傳入的日期時間進行判斷,如是否為一年內,幾個月之內,幾天前,幾天之內等等的需求。
如要求前端傳入的日期是要為當前日期一年內的某個日期,基于jdk8的LocalDateTime or LocalDate等常用的做法如下:
1
2
3
4
5
6
7
|
// 前端傳字符串如‘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結合來解決此類日期時間的范圍校驗。
DateTimeRange.java 用于LocalDateTime or String類型日期時間范圍校驗
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
83
84
85
86
87
88
89
90
91
|
/** * 日期時間范圍校驗注解,可作用于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<DateTimeRange, Object> { 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 ; } } } |
DateRange.java 用于LocalDate or String類型日期范圍校驗
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
83
84
85
86
87
88
89
90
91
92
93
94
|
/** * 日期范圍校驗,作用于 {@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<DateRange, Object> { 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 ; } } } |
RangeUnit.java 范圍單位枚舉,用于以上兩注解的unit屬性
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
|
/** * @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 ; } } } |
測試類
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
|
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
以上這篇javax.validation自定義日期范圍校驗注解操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/mayfly_hml/article/details/107311368