日期:2014-05-17 浏览次数:20973 次
public static void main(String[] args)throws Exception { String arr[] = { "2011", "2011-8", "2011-08-9","2011-8-9 9", "2011-8-9 9:10", "2011-8-09 19:08:25" }; for(int i=0;i<arr.length;i++){ String standard = toStandard(arr[i]); System.out.println(standard); } } static String toStandard(String str){ String[] dateTime = str.split("\\s"); String date = dateTime[0]; String time = dateTime.length>1?dateTime[1]:""; return toStandardDate(date) +" "+ toStandardTime(time); } static String toStandardDate(String date){ String ymd[] = date.split("-"); String year = ymd[0]; String month = ymd.length>1?fill(ymd[1]):"01"; String day = ymd.length>2?fill(ymd[2]):"01"; return year +"-"+month+"-"+day; } static String toStandardTime(String time){ String[] hms = time.split(":"); String hh = hms.length>0?fill(hms[0]):"00"; String mm = hms.length>1?fill(hms[1]):"00"; String ss = hms.length>2?fill(hms[2]):"00"; return hh+":"+mm+":"+ss; } static String fill(String str) { if(str.length() == 2){ return str; }else if(str.length() == 1){ return "0"+str; }else if(str.length() == 0){ return "00"; } throw new IllegalArgumentException("参数不合法!"); }
------解决方案--------------------
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=format.parse(s);
String str=format.format(date);