1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.integration.beans;
21
22 import java.beans.PropertyEditor;
23 import java.text.DateFormat;
24 import java.text.ParseException;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
27 import java.util.Locale;
28 import java.util.regex.Pattern;
29
30
31
32
33
34
35
36 public class DateEditor extends AbstractPropertyEditor {
37 private static final Pattern MILLIS = Pattern.compile("[0-9][0-9]*");
38
39 private final DateFormat[] formats = new DateFormat[] {
40 new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH),
41 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ENGLISH),
42 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH),
43 new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH), new SimpleDateFormat("yyyy-MM", Locale.ENGLISH),
44 new SimpleDateFormat("yyyy", Locale.ENGLISH), };
45
46
47
48
49 public DateEditor() {
50 for (DateFormat f : formats) {
51 f.setLenient(true);
52 }
53 }
54
55
56
57
58 @Override
59 protected String toText(Object value) {
60 if (value instanceof Number) {
61 long time = ((Number) value).longValue();
62
63 if (time <= 0) {
64 return null;
65 }
66
67 value = new Date(time);
68 }
69
70 return formats[0].format((Date) value);
71 }
72
73
74
75
76 @Override
77 protected Object toValue(String text) {
78 if (MILLIS.matcher(text).matches()) {
79 long time = Long.parseLong(text);
80
81 if (time <= 0) {
82 return null;
83 }
84
85 return new Date(time);
86 }
87
88 for (DateFormat f : formats) {
89 try {
90 return f.parse(text);
91 } catch (ParseException e) {
92 throw new IllegalArgumentException("Wrong date: " + text);
93 }
94 }
95
96 throw new IllegalArgumentException("Wrong date: " + text);
97 }
98 }