1 package org.kuali.student.r2.common.util.date;
2
3 import org.joda.time.DateTime;
4 import org.joda.time.format.DateTimeFormat;
5 import org.joda.time.format.DateTimeFormatter;
6
7 import java.util.Date;
8
9 /**
10 * Helper class that wraps jada's DateTimeFormatter. Has helper methods to mimic standard java methods and make
11 * refactoring cleaner
12 *
13 * User: gtaylor
14 * Date: 11/6/12
15 * Time: 2:47 PM
16 */
17 public class KSDateTimeFormatter {
18
19 protected DateTimeFormatter formatter;
20 protected String pattern;
21
22 /**
23 * Creates a new formatter
24 *
25 * @param pattern regex pattern for the format
26 */
27 public KSDateTimeFormatter(String pattern) {
28 try{
29 this.pattern = pattern;
30
31 this.formatter = DateTimeFormat.forPattern(pattern);
32 }
33 catch (IllegalArgumentException ex){
34
35 throw new IllegalArgumentException("Illegal pattern cannot be parsed. pattern["+ pattern +"].");
36 }
37
38 }
39
40 /**
41 * Helper method that allows for a straight string to java.util.Date conversion.
42 * returns null if it cannot parse the string
43 *
44 * @param stringDate
45 * @return A java.util.Date, or null if the input could not be parsed
46 * @throws UnsupportedOperationException if parsing is not supported
47 * @throws IllegalArgumentException if the text to parse is invalid
48 */
49 public Date parse(String stringDate){
50 Date dRet = null;
51
52 try{
53 DateTime dt = formatter.parseDateTime(stringDate);
54 dRet = dt.toDate();
55 }catch (IllegalArgumentException ex){
56 dRet = null;
57 throw new IllegalArgumentException(stringDate + " cannot be parsed with pattern["+ this.pattern +"].");
58 }
59
60 return dRet;
61 }
62
63 /**
64 * Helper method that allows a stright java.util.Date to String converstion
65 * @param javaDate
66 * @return
67 * @throws IllegalArgumentException if the javaDate is invalid
68 */
69 public String format(Date javaDate){
70 return this.formatter.print(new DateTime(javaDate));
71 }
72
73 /**
74 * Helper method that allows a stright java.util.Date to String converstion
75 * @param strDate
76 * @return
77 * @throws IllegalArgumentException if the javaDate is invalid
78 */
79 public String format(String strDate){
80 return this.formatter.print(new DateTime(strDate));
81 }
82
83 /**
84 * Get underlying Jada formatter
85 *
86 * @return
87 */
88 public DateTimeFormatter getFormatter(){
89 return formatter;
90 }
91
92 /**
93 * This returns the pattern used to create the formatter
94 *
95 * @return
96 */
97 public String getPattern() {
98 return pattern;
99 }
100 }