今天在导入中碰见时间格式的问题写了一个测试类,共享一下
public static void main(String[] args) { String dateStr="2015/1/7 14:32"; String out =DateUtils.formatDateStr(dateStr, "yyyy-MM-dd HH:mm"); System.out.println(out); } static class DateUtils{ public static String formatDateStr(String date, String format) { Date d = StringUtils.parseDate(date, format); if (d == null) return ""; else return (new SimpleDateFormat(format)).format(d); } } static class StringUtils { public static Date parseDate(String str, String parsePattern) { if (str == null || "".equals(str)) return null; SimpleDateFormat parser = new SimpleDateFormat(parsePattern); ParsePosition pos = new ParsePosition(0); Date date = parser.parse(str, pos); if (date != null) return date; else throw new BusinessRuntimeException((new StringBuilder()) .append("u65E5u671Fu9519u8BEF: ").append(str) .toString()); } }
dateStr在执行的时候会报错,希望和大家交流一下时间处理技巧