View Javadoc

1   /*
2    * Copyright 2004 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.ancientprogramming.fixedformat4j.format.impl;
17  
18  import com.ancientprogramming.fixedformat4j.exception.FixedFormatException;
19  import com.ancientprogramming.fixedformat4j.format.AbstractFixedFormatter;
20  import com.ancientprogramming.fixedformat4j.format.FormatInstructions;
21  import org.apache.commons.lang.StringUtils;
22  
23  import java.text.DateFormat;
24  import java.text.ParseException;
25  import java.text.SimpleDateFormat;
26  import java.util.Date;
27  
28  /**
29   * Formatter for {@link java.util.Date} data
30   *
31   * @author Jacob von Eyben - http://www.ancientprogramming.com
32   * @since 1.0.0
33   */
34  public class DateFormatter extends AbstractFixedFormatter<Date> {
35  
36    public Date asObject(String string, FormatInstructions instructions) throws FixedFormatException {
37      Date result = null;
38  
39      if (!StringUtils.isEmpty(string)) {
40        try {
41          result = getFormatter(instructions.getFixedFormatPatternData().getPattern()).parse(string);
42        } catch (ParseException e) {
43          throw new FixedFormatException("Could not parse value[" + string + "] by pattern[" + instructions.getFixedFormatPatternData().getPattern() + "] to " + Date.class.getName());
44        }
45      }
46      return result;
47    }
48  
49    public String asString(Date date, FormatInstructions instructions) {
50      String result = null;
51      if (date != null) {
52        result = getFormatter(instructions.getFixedFormatPatternData().getPattern()).format(date);
53      }
54      return result;
55    }
56  
57    DateFormat getFormatter(String pattern) {
58      return new SimpleDateFormat(pattern);
59    }
60  }