View Javadoc
1   /*
2    * CSVeed (https://github.com/42BV/CSVeed)
3    *
4    * Copyright 2013-2023 CSVeed.
5    *
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of The Apache Software License,
8    * Version 2.0 which accompanies this distribution, and is available at
9    * https://www.apache.org/licenses/LICENSE-2.0.txt
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   * The Class DateConverter.
22   */
23  public class DateConverter extends AbstractConverter<Date> {
24  
25      /** The date format. */
26      private final DateFormat dateFormat;
27  
28      /** The allow empty. */
29      private final boolean allowEmpty;
30  
31      /** The exact date length. */
32      private final int exactDateLength;
33  
34      /** The format text. */
35      private final String formatText;
36  
37      /**
38       * Instantiates a new date converter.
39       *
40       * @param formatText
41       *            the format text
42       * @param allowEmpty
43       *            the allow empty
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  }