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 straight java.util.Date to String conversion
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 * Formats a Joda DateTime as a String.
75 * @param dateTime
76 * @return
77 */
78 public String format(DateTime dateTime) {
79 return this.formatter.print(dateTime);
80 }
81
82 /**
83 * Helper method that allows a straight java.util.Date to String conversion
84 * @param strDate
85 * @return
86 * @throws IllegalArgumentException if the javaDate is invalid
87 */
88 public String format(String strDate){
89 return this.formatter.print(new DateTime(strDate));
90 }
91
92 /**
93 * Get underlying Jada formatter
94 *
95 * @return
96 */
97 public DateTimeFormatter getFormatter(){
98 return formatter;
99 }
100
101 /**
102 * This returns the pattern used to create the formatter
103 *
104 * @return
105 */
106 public String getPattern() {
107 return pattern;
108 }
109 }