View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
17   */
18  
19  package org.mycore.frontend.xeditor.validation;
20  
21  import java.text.ParsePosition;
22  import java.text.SimpleDateFormat;
23  import java.util.ArrayList;
24  import java.util.Date;
25  import java.util.List;
26  import java.util.Locale;
27  
28  import org.mycore.common.MCRException;
29  
30  /**
31   * Helper for date validators to convert string input into a date value.
32   * 
33   * @author Frank L\u00FCtzenkirchen 
34   */
35  public class MCRDateConverter {
36  
37      private static final Date CHECK_DATE = new Date(0L);
38  
39      private List<SimpleDateFormat> formats = new ArrayList<>();
40  
41      /**
42       * @param patterns a list of allowed SimpleDateFormat patterns separated by ";" 
43       */
44      public MCRDateConverter(String patterns) {
45          for (String pattern : patterns.split(";")) {
46              formats.add(getDateFormat(pattern.trim()));
47          }
48      }
49  
50      protected SimpleDateFormat getDateFormat(String pattern) {
51          SimpleDateFormat df = new SimpleDateFormat(pattern, Locale.ROOT);
52          df.setLenient(false);
53          return df;
54      }
55  
56      /**
57       * 
58       * @param input the text string
59       * @return the parsed Date matching one of the allowed date patterns, or null if the text can not be parsed
60       */
61      public Date string2date(String input) throws MCRException {
62          for (SimpleDateFormat format : formats) {
63              if (format.format(CHECK_DATE).length() != input.length()) {
64                  continue;
65              }
66              try {
67                  ParsePosition pp = new ParsePosition(0);
68                  Date value = format.parse(input, pp);
69                  if (pp.getIndex() == input.length()) {
70                      return value;
71                  }
72              } catch (Exception ignored) {
73              }
74          }
75  
76          return null;
77      }
78  }