因为数据来自各个系统。
时间格式可能是
2014/11/5 10:09
2014/11/5 10:09:08
2014-11-5 10:09
2014-11-5 10:09:08
四种格式。
需要将其转换成date对象
代码很简答,事先生成多个simpleDateFormat
一次转换,成功就跳出循环,发生异常就用下一个转换。
public class DateFormatUtil {
private static List<SimpleDateFormat> list=new ArrayList<SimpleDateFormat>();
static{
String date1="yyyy-MM-dd";
String date2="yyyy/MM/dd";
String time1="hh:mm";
String time2="hh:mm:ss";
list.add(new SimpleDateFormat(date1+" "+time2));
list.add(new SimpleDateFormat(date1+" "+time1));
list.add(new SimpleDateFormat(date2+" "+time1));
list.add(new SimpleDateFormat(date2+" "+time2));
}
public static void main(String[] args) throws ParseException {
System.out.println(formatDate("2014-10-1 10:35"));
System.out.println(formatDate("2014/10/1 10:35:23"));
}
public static Date formatDate(String source){
Date date=null;
for(SimpleDateFormat df:list){
try{
date=df.parse(source);
}catch(Exception e){
continue;
}
}
return date;
}
}