1 4 package org.oddjob.util; 5 6 import java.text.ParseException ; 7 import java.text.SimpleDateFormat ; 8 import java.util.Calendar ; 9 import java.util.Date ; 10 import java.util.TimeZone ; 11 12 import org.oddjob.OJConstants; 13 14 19 public class DateHelper { 20 21 30 public static Date parseDateTime(String text) throws ParseException { 31 return parseDateTime(text, TimeZone.getDefault()); 32 } 33 34 44 public static Date parseDateTime(String text, String timeZoneId) 45 throws ParseException { 46 TimeZone timeZone = TimeZone.getDefault(); 47 if (timeZoneId != null) { 48 timeZone = TimeZone.getTimeZone(timeZoneId); 49 } 50 return parseDateTime(text, timeZone); 51 } 52 53 63 public static Date parseDateTime(String text, TimeZone timeZone) 64 throws ParseException { 65 if (text.indexOf(' ') == -1) { 66 return parseDate(text, timeZone); 67 } 68 else { 69 try { 70 return parse(text, OJConstants.DATE_FORMAT + " " 71 + OJConstants.TIME_FORMAT1, timeZone); 72 } catch (ParseException e) { 73 try { 74 return parse(text, OJConstants.DATE_FORMAT + " " 75 + OJConstants.TIME_FORMAT2, timeZone); 76 } catch (ParseException e2) { 77 return parse(text, OJConstants.DATE_FORMAT + " " 78 + OJConstants.TIME_FORMAT3, timeZone); 79 } 80 } 81 } 82 } 83 84 92 public static Date parseDate(String text) throws ParseException { 93 return parseDate(text, TimeZone.getDefault()); 94 } 95 96 106 public static Date parseDate(String text, String timeZoneId) throws ParseException { 107 TimeZone timeZone = TimeZone.getDefault(); 108 if (timeZoneId != null) { 109 timeZone = TimeZone.getTimeZone(timeZoneId); 110 } 111 return parseDate(text, timeZone); 112 } 113 114 123 public static Date parseDate(String text, TimeZone timeZone) throws ParseException { 124 return parse(text, OJConstants.DATE_FORMAT, timeZone); 125 } 126 127 134 public static long parseTime(String text) throws ParseException { 135 TimeZone timeZone = TimeZone.getTimeZone("GMT+00"); 136 Date d = null; 137 try { 138 d = parse(text, OJConstants.TIME_FORMAT1, timeZone); 139 } catch (ParseException e) { 140 try { 141 d = parse(text, OJConstants.TIME_FORMAT2, timeZone); 142 } catch (ParseException e2) { 143 d = parse(text, OJConstants.TIME_FORMAT3, timeZone); 144 } 145 } 146 return d.getTime(); 147 } 148 149 155 public static String formatDate(Date date) { 156 return new SimpleDateFormat (OJConstants.DATE_FORMAT).format(date); 157 } 158 159 160 169 static Date parse(String text, String format, TimeZone timeZone) throws ParseException { 170 SimpleDateFormat f = new SimpleDateFormat (format); 171 f.setTimeZone(timeZone); 172 173 Date d = f.parse(text); 174 175 Calendar c = Calendar.getInstance(); 176 c.setTimeZone(timeZone); 177 c.setTime(d); 178 179 int year = c.get(Calendar.YEAR); 180 if (year < 50) { 181 year = year + 2000; 182 } 183 else if (year < 100) { 184 year = year + 1900; 185 } 186 187 c.set(Calendar.YEAR, year); 188 return c.getTime(); 189 } 190 191 } 192 193 194 | Popular Tags |