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
37 public class DateEditor extends AbstractPropertyEditor {
38 private static final Pattern MILLIS = Pattern.compile("[0-9][0-9]*");
39
40 private final DateFormat[] formats = new DateFormat[] {
41 new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH),
42 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ENGLISH),
43 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH),
44 new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH),
45 new SimpleDateFormat("yyyy-MM", Locale.ENGLISH),
46 new SimpleDateFormat("yyyy", Locale.ENGLISH),
47 };
48
49 public DateEditor() {
50 for (DateFormat f: formats) {
51 f.setLenient(true);
52 }
53 }
54
55 @Override
56 protected String toText(Object value) {
57 if (value instanceof Number) {
58 long time = ((Number) value).longValue();
59 if (time <= 0) {
60 return null;
61 }
62 value = new Date(time);
63 }
64 return formats[0].format((Date) value);
65 }
66
67 @Override
68 protected Object toValue(String text) throws IllegalArgumentException {
69 if (MILLIS.matcher(text).matches()) {
70 long time = Long.parseLong(text);
71 if (time <= 0) {
72 return null;
73 }
74 return new Date(time);
75 }
76
77 for (DateFormat f: formats) {
78 try {
79 return f.parse(text);
80 } catch (ParseException e) {
81 }
82 }
83
84 throw new IllegalArgumentException("Wrong date: " + text);
85 }
86 }