1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.myfaces.tobago.internal.util;
21
22 import javax.faces.convert.ConverterException;
23 import javax.faces.convert.DateTimeConverter;
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.Locale;
27
28
29
30
31
32 public final class DateFormatUtils {
33
34 private static final String TYPE_DATE = "date";
35 private static final String TYPE_TIME = "time";
36 private static final String TYPE_BOTH = "both";
37 private static final String STYLE_DEFAULT = "default";
38 private static final String STYLE_MEDIUM = "medium";
39 private static final String STYLE_SHORT = "short";
40 private static final String STYLE_LONG = "long";
41 private static final String STYLE_FULL = "full";
42
43 private DateFormatUtils() {
44 }
45
46
47
48
49
50
51
52
53 public static String findPattern(final DateTimeConverter converter) {
54 String pattern = converter.getPattern();
55
56 if (pattern == null) {
57 final DateFormat dateFormat = getDateFormat(
58 converter.getType(), converter.getDateStyle(),
59 converter.getTimeStyle(), converter.getLocale());
60 if (dateFormat instanceof SimpleDateFormat) {
61 final SimpleDateFormat format = (SimpleDateFormat) dateFormat;
62 pattern = format.toPattern();
63 }
64 }
65
66 return pattern;
67 }
68
69 private static DateFormat getDateFormat(
70 final String type, final String dateStyle, final String timeStyle, final Locale locale) {
71 final DateFormat format;
72 if (type.equals(TYPE_DATE)) {
73 format = DateFormat.getDateInstance(calcStyle(dateStyle), locale);
74 } else if (type.equals(TYPE_TIME)) {
75 format = DateFormat.getTimeInstance(calcStyle(timeStyle), locale);
76 } else if (type.equals(TYPE_BOTH)) {
77 format = DateFormat.getDateTimeInstance(calcStyle(dateStyle),
78 calcStyle(timeStyle),
79 locale);
80 } else {
81 throw new ConverterException("invalid type '" + type + "'");
82 }
83
84
85 format.setLenient(false);
86 return format;
87 }
88
89 private static int calcStyle(final String name) {
90 if (name.equals(STYLE_DEFAULT)) {
91 return DateFormat.DEFAULT;
92 }
93 if (name.equals(STYLE_MEDIUM)) {
94 return DateFormat.MEDIUM;
95 }
96 if (name.equals(STYLE_SHORT)) {
97 return DateFormat.SHORT;
98 }
99 if (name.equals(STYLE_LONG)) {
100 return DateFormat.LONG;
101 }
102 if (name.equals(STYLE_FULL)) {
103 return DateFormat.FULL;
104 }
105
106 throw new ConverterException("invalid style '" + name + "'");
107 }
108
109 }