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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.regex.Pattern;
public class ApiUtis { private static HashMap<String,String> dateRegFormat; static { dateRegFormat = new HashMap<String, String>(); dateRegFormat.put("^\\d{4}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D*$", "yyyy-MM-dd-HH-mm-ss"); dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}$","yyyy-MM-dd-HH-mm"); dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}$","yyyy-MM-dd-HH"); dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}$","yyyy-MM-dd"); dateRegFormat.put("^\\d{4}\\D+\\d{2}$","yyyy-MM"); dateRegFormat.put("^\\d{4}$","yyyy"); dateRegFormat.put("^\\d{14}$","yyyyMMddHHmmss"); dateRegFormat.put("^\\d{12}$","yyyyMMddHHmm"); dateRegFormat.put("^\\d{10}$","yyyyMMddHH"); dateRegFormat.put("^\\d{8}$","yyyyMMdd"); dateRegFormat.put("^\\d{6}$","yyyyMM"); dateRegFormat.put("^\\d{2}\\s*:\\s*\\d{2}\\s*:\\s*\\d{2}$","yyyy-MM-dd-HH-mm-ss"); dateRegFormat.put("^\\d{2}\\s*:\\s*\\d{2}$","yyyy-MM-dd-HH-mm"); dateRegFormat.put("^\\d{2}\\D+\\d{1,2}\\D+\\d{1,2}$","yy-MM-dd"); dateRegFormat.put("^\\d{1,2}\\D+\\d{1,2}$","yyyy-dd-MM"); dateRegFormat.put("^\\d{1,2}\\D+\\d{1,2}\\D+\\d{4}$","dd-MM-yyyy"); } @SuppressWarnings("finally") public static String FormatDate(String dateStr){ String curDate =new SimpleDateFormat("yyyy-MM-dd").format(new Date()); DateFormat formatter1 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat formatter2; String dateReplace; String strSuccess=""; try{ for(String key : dateRegFormat.keySet()) { if(Pattern.compile(key).matcher(dateStr).matches()) { formatter2= new SimpleDateFormat(dateRegFormat.get(key)); if(key.equals("^\\d{2}\\s*:\\s*\\d{2}\\s*:\\s*\\d{2}$")||key.equals("^\\d{2}\\s*:\\s*\\d{2}$")){ dateStr= curDate + "-"+ dateStr; }else if(key.equals("^\\d{1,2}\\D+\\d{1,2}$")){ dateStr = curDate.substring(0,4)+ "-"+ dateStr; } dateReplace= dateStr.replaceAll("\\D+","-"); strSuccess= formatter1.format(formatter2.parse(dateReplace)); break; } } }catch(Exception e) { System.err.println("-----------------日期格式无效:"+dateStr); throw new Exception( "日期格式无效"); } finally{ return strSuccess; } } }
|