1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
30
31
32
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 }