1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class DateConverter { public static Date parseDate(String dateStr, String format) throws ParseException { return new Date(new SimpleDateFormat(format).parse(dateStr).getTime()); } public static String formatDate(Date date, String format) { return new SimpleDateFormat(format).format(date); } public Date convert(String source) { if (source == null) return null; source = source.trim(); if ("".equals(source)) return null; try { if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) return parseDate(source, "yyyy-MM-dd"); else if (source.matches("^\\d{4}/\\d{1,2}/\\d{1,2}$")) return parseDate(source, "yyyy/MM/dd"); else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}$")) return parseDate(source, "yyyy-MM-dd HH:mm:ss"); else if (source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}$")) return parseDate(source, "yyyy/MM/dd HH:mm:ss"); else throw new IllegalArgumentException("Invalid date value '" + source + "'"); } catch (ParseException e) { e.printStackTrace(); } return null; } }
|