JAVA 中:
坑一:
replace没有用对象进行接收。直接使用
dateStr.replaceAll("\/", "-");
是不行的,至少得加上 "dateStr = " 。
坑二:
正则匹配斜杠
\d{4}\\\d{1,2}\\\d{1,2} 2016 5 5
中间得加6个斜杠转义。自行体会吧,都是泪啊,太隐蔽了……
坑三:
测试的时候没有转义斜杠
dealVenueDate("2016\06\07"),defaultDatePattern
基本的坑,没留意掉进去了
坑四:
正则匹配中文,要使用Unicode。不烦述。
public static String defaultDatePattern = "yyyy-MM-dd"; public Date dealVenueDate(String dateStr){ Date date = null; String temp = ""; if(StringUtils.isBlank(dateStr)){ return date; } String format = "\d{4}-\d{2}-\d{2}|\d{4}\/\d{1,2}\/\d{1,2}|\d{4}\\\d{1,2}\\\d{1,2}";// 2016-05-05 2016/05/05 Pattern pattern = Pattern.compile(format); Matcher matcher = pattern.matcher(dateStr); String format1 = "\d{1,2}\/\d{1,2}\/\d{2}";// 5/5/16 05/05/16 Pattern pattern1 = Pattern.compile(format1); Matcher matcher1 = pattern1.matcher(dateStr); // String format2 = "\d{1,2}\[月]\d{1,2}\[日]";// 5月5日 // Pattern pattern2 = Pattern.compile(format2); // Matcher matcher2 = pattern2.matcher(dateStr); try { if(matcher.matches()){ if(dateStr.contains("\")){ dateStr = dateStr.replaceAll("\\", "-"); } if(dateStr.contains("/")){ dateStr = dateStr.replaceAll("\/", "-"); } date = parse(dateStr,defaultDatePattern); }else if(matcher1.matches()){ temp = dateStr.substring(dateStr.length()-2,dateStr.length()); String midTemp = dateStr.substring(0,dateStr.length()-3); midTemp = midTemp.replaceAll("\/", "-"); temp = "20" + temp + "-" + midTemp; date = parse(temp,defaultDatePattern); }else if(dateStr.indexOf("月") > 0 && dateStr.indexOf("日") > 0){//5月5日 temp = dateStr.substring(0,dateStr.indexOf("日")); String[] data = temp.split("月"); if(data != null && data.length == 2){ Calendar cal = Calendar.getInstance(); String year = cal.get(Calendar.YEAR) + ""; temp = year + "-" + data[0] + "-" + data[1]; date = parse(temp,defaultDatePattern); } } } catch (Exception e) { e.printStackTrace(); } return date ; } public static Date parse(String strDate, String pattern) throws ParseException { SimpleDateFormat df = new SimpleDateFormat(pattern); return df.parse(strDate); } public static String format(Date date, String pattern) { String returnValue = ""; if (date != null) { SimpleDateFormat df = new SimpleDateFormat(pattern); returnValue = df.format(date); } return returnValue; } public static void main(String[] args) { // SimpleDateFormat df = new SimpleDateFormat(defaultDatePattern); // try { // System.out.println("=========aaaaaa========"+df.parse("2016\06\07")); // } catch (ParseException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // System.out.println("=========aaaaaa========"+format(dealVenueDate("2016\06\07"),defaultDatePattern)); // System.out.println("=========aaaaaa========"+format(dealVenueDate("2016/06/07"),defaultDatePattern)); // System.out.println("=========aaaaaa========"+format(dealVenueDate("6/7/16"),defaultDatePattern)); // System.out.println("=========aaaaaa========"+format(dealVenueDate("5月10日"),defaultDatePattern)); }