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