1
2
3
4
5
6
7
8
9
10
11 package org.csveed.bean.conversion;
12
13 import static org.csveed.bean.conversion.ConversionUtil.hasText;
14
15 import java.text.DateFormat;
16 import java.text.ParseException;
17 import java.text.SimpleDateFormat;
18 import java.util.Date;
19
20
21
22
23 public class DateConverter extends AbstractConverter<Date> {
24
25
26 private final DateFormat dateFormat;
27
28
29 private final boolean allowEmpty;
30
31
32 private final int exactDateLength;
33
34
35 private final String formatText;
36
37
38
39
40
41
42
43
44
45 public DateConverter(String formatText, boolean allowEmpty) {
46 super(Date.class);
47 this.formatText = formatText;
48 this.dateFormat = new SimpleDateFormat(formatText);
49 this.dateFormat.setLenient(false);
50 this.allowEmpty = allowEmpty;
51 this.exactDateLength = -1;
52 }
53
54 @Override
55 public Date fromString(String text) throws Exception {
56 if (this.allowEmpty && !hasText(text)) {
57 return null;
58 }
59 if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
60 throw new IllegalArgumentException(
61 "Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
62 }
63 try {
64 return this.dateFormat.parse(text);
65 } catch (ParseException ex) {
66 throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
67 }
68 }
69
70 @Override
71 public String infoOnType() {
72 return super.infoOnType() + " " + formatText;
73 }
74
75 @Override
76 public String toString(Date value) {
77 return value != null ? this.dateFormat.format(value) : "";
78 }
79
80 }