1 3 package jodd.datetime.formatter; 4 5 import jodd.datetime.DateTimeStamp; 6 import jodd.datetime.JDateTime; 7 8 27 public abstract class AbstractFormatter implements JdtFormatter { 28 29 34 protected char[][] patterns; 35 36 39 protected char ESCAPE_CHAR = '\''; 40 41 42 45 protected void preparePatterns(String [] spat) { 46 patterns = new char[spat.length][]; 47 for (int i = 0; i < spat.length; i++) { 48 patterns[i] = spat[i].toCharArray(); 49 } 50 } 51 52 61 protected int findPattern(char[] format, int i) { 62 int frmtc_len = format.length; 63 boolean match; 64 int n, lastn = -1; 65 int maxLen = 0; 66 for (n = 0; n < patterns.length; n++) { 67 char[] curr = patterns[n]; if (i > frmtc_len - curr.length) { 69 continue; 70 } 71 match = true; 72 int delta = 0; 73 while (delta < curr.length) { if (curr[delta] != format[i + delta]) { 75 match = false; break; 77 } 78 delta++; 79 } 80 if (match == true) { if (patterns[n].length > maxLen) { lastn = n; 83 maxLen = patterns[n].length; 84 } 85 } 86 } 87 return lastn; 88 } 89 90 92 99 protected abstract String convertPattern(int patternIndex, JDateTime jdt); 100 101 104 public String convert(JDateTime jdt, String format) { 105 char[] fmtc = format.toCharArray(); 106 int fmtc_len = fmtc.length; 107 StringBuffer result = new StringBuffer (fmtc_len); 108 109 int i = 0; 110 while (i < fmtc_len) { 111 if (fmtc[i] == ESCAPE_CHAR) { int end = i + 1; 113 while (end < fmtc_len) { 114 if (fmtc[end] == ESCAPE_CHAR) { if (end + 1 < fmtc_len) { 116 end++; 117 if (fmtc[end] == ESCAPE_CHAR) { result.append(ESCAPE_CHAR); } else { 120 break; 121 } 122 } 123 } else { 124 result.append(fmtc[end]); 125 } 126 end++; 127 } 128 i = end; 129 continue; } 131 132 int n = findPattern(fmtc, i); 133 if (n != -1) { result.append(convertPattern(n, jdt)); 135 i += patterns[n].length; 136 } else { 137 result.append(fmtc[i]); 138 i++; 139 } 140 } 141 return result.toString(); 142 } 143 144 146 156 protected abstract void parseValue(int patternIndex, String value, DateTimeStamp destination); 157 158 161 public DateTimeStamp parse(String string, String format) { 162 char[] sc = string.toCharArray(); 163 char[] fc = format.toCharArray(); 164 165 int i = 0, j = 0; 166 int slen = string.length(); 167 int tlen = format.length(); 168 169 DateTimeStamp time = new DateTimeStamp(); 170 171 while (true) { 172 int n = findPattern(fc, i); 173 if (n != -1) { i += patterns[n].length; 175 StringBuffer w = new StringBuffer (); 176 char next = 0xFFFF; 177 if (i < tlen) { 178 next = fc[i]; } 180 while ((j < slen) && (sc[j] != next)) { 181 w.append(sc[j]); 182 j++; 183 } 184 try { 185 parseValue(n, w.toString(), time); 186 } catch (NumberFormatException nfe) { 187 return null; 188 } 189 } else { 190 if (fc[i] == sc[j]) { 191 j++; 192 } 193 i++; 194 } 195 if ((i == tlen) || (j == slen)) { 196 break; 197 } 198 } 199 return time; 200 } 201 } 202 | Popular Tags |