1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.xbean.propertyeditor;
18
19 import java.text.DateFormat;
20 import java.text.ParseException;
21 import java.text.SimpleDateFormat;
22 import java.util.Date;
23 import java.util.Locale;
24 import java.util.List;
25 import java.util.ArrayList;
26
27
28
29
30
31
32 public class DateEditor extends AbstractConverter {
33
34 private List<DateFormat> formats = new ArrayList<DateFormat>();
35
36 public DateEditor() {
37 super(Date.class);
38
39 formats.add(DateFormat.getInstance());
40 formats.add(DateFormat.getDateInstance());
41 formats.add(new SimpleDateFormat("yyyy-MM-dd"));
42 formats.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"));
43 }
44
45
46
47
48
49
50
51
52 protected Object toObjectImpl(String text) {
53 for (DateFormat format : formats) {
54 try {
55 return format.parse(text);
56 } catch (ParseException e) {
57 }
58 }
59
60 try {
61 return complexParse(text);
62 } catch (ParseException e) {
63
64
65 throw new PropertyEditorException(e);
66 }
67 }
68
69 private Object complexParse(String text) throws ParseException {
70
71
72
73 Locale locale = Locale.getDefault();
74 int style = DateFormat.MEDIUM;
75 int firstSpaceIndex = text.indexOf(' ');
76 if (firstSpaceIndex != -1) {
77 String token = text.substring(0, firstSpaceIndex).intern();
78 if (token.startsWith("locale")) {
79 String localeStr = token.substring(token.indexOf('=') + 1);
80 int underscoreIndex = localeStr.indexOf('_');
81 if (underscoreIndex != -1) {
82 String language = localeStr.substring(0, underscoreIndex);
83 String country = localeStr.substring(underscoreIndex + 1);
84 locale = new Locale(language, country);
85 } else {
86 locale = new Locale(localeStr);
87 }
88
89 int nextSpaceIndex = text.indexOf(' ', firstSpaceIndex + 1);
90 token = text.substring(firstSpaceIndex + 1, nextSpaceIndex);
91 String styleStr = token.substring(token.indexOf('=') + 1);
92 if (styleStr.equalsIgnoreCase("SHORT")) {
93 style = DateFormat.SHORT;
94 } else if (styleStr.equalsIgnoreCase("MEDIUM")) {
95 style = DateFormat.MEDIUM;
96 } else if (styleStr.equalsIgnoreCase("LONG")) {
97 style = DateFormat.LONG;
98 } else if (styleStr.equalsIgnoreCase("FULL")) {
99 style = DateFormat.FULL;
100 } else {
101
102
103 style = DateFormat.MEDIUM;
104 }
105 text = text.substring(nextSpaceIndex + 1);
106 }
107 }
108 DateFormat formats = DateFormat.getDateInstance(style, locale);
109 return formats.parse(text);
110 }
111
112 protected String toStringImpl(Object value) {
113 Date date = (Date) value;
114 String text = formats.get(0).format(date);
115 return text;
116 }
117 }