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 package info.magnolia.ui.field;
35
36 import info.magnolia.ui.field.factory.DateFieldFactory;
37
38 import java.time.LocalDate;
39 import java.time.LocalDateTime;
40 import java.time.format.DateTimeFormatter;
41 import java.time.temporal.Temporal;
42 import java.util.Date;
43 import java.util.Optional;
44
45
46
47
48 @FieldType("dateField")
49 public class DateFieldDefinition extends ConfiguredFieldDefinition<Object> {
50
51 public static final String NOW = "now";
52
53 private boolean time = false;
54
55 private String dateFormat = "yyyy-MM-dd";
56
57 private String timeFormat = "HH:mm";
58
59 public DateFieldDefinition() {
60 setFactoryClass(DateFieldFactory.class);
61 setType(Date.class);
62 setFieldBinderClass(DateFieldBinder.class);
63 }
64
65 public void init() {
66 Optional.ofNullable(super.getDefaultValue())
67 .map(String::valueOf)
68 .flatMap(this::asTemporal).ifPresent(this::setDefaultValue);
69 }
70
71 public boolean isTime() {
72 return time;
73 }
74
75 public void setTime(boolean time) {
76 this.time = time;
77 }
78
79 public String getDateFormat() {
80 return dateFormat;
81 }
82
83 public void setDateFormat(String dateFormat) {
84 this.dateFormat = dateFormat;
85 }
86
87 public String getTimeFormat() {
88 return timeFormat;
89 }
90
91 public void setTimeFormat(String timeFormat) {
92 this.timeFormat = timeFormat;
93 }
94
95 private Optional<Temporal> asTemporal(String defaultValue) {
96 if (NOW.equalsIgnoreCase(defaultValue)) {
97 return Optional.of(LocalDateTime.now());
98 }
99
100 if (isTime()) {
101 return Optional.of(LocalDateTime.parse(defaultValue, DateTimeFormatter.ofPattern(getDateFormat() + " " + getTimeFormat())));
102 } else {
103 return Optional.of(LocalDate.parse(defaultValue, DateTimeFormatter.ofPattern(getDateFormat())));
104 }
105 }
106 }