因为需求,只写了年月日时的自动转换。
public static Date convertStringToDate(String time) {
String separator_yM = "";
String separator_Md = "";
String separator_dH = "";
String yyyy = "";
String MM = "";
String dd = "";
String HH = "";
Pattern pattern = Pattern
.compile("(\\d{4})([^\\d]?)(\\d{1,2})([^\\d]?)(\\d{1,2})([^\\d]?)(\\d*)$");
Matcher matcher = pattern.matcher(time);
if (matcher.find()) {
System.out.println(matcher.group(0));
yyyy = matcher.group(1);
separator_yM = matcher.group(2);
MM = matcher.group(3);
separator_Md = matcher.group(4);
dd = matcher.group(5);
separator_dH = matcher.group(6);
HH = matcher.group(7);
System.out.println(yyyy + separator_yM + MM + separator_Md + dd + separator_dH + HH);
}
if(yyyy == null || yyyy.equals("")
|| MM == null || MM.equals("")
|| dd == null || dd.equals("")) {
return null;
}
String formateStr = "yyyy" + separator_yM + repeat("M", MM.length()) + separator_Md + repeat("d", dd.length()) + separator_dH + repeat("H", HH.length());
System.out.println("formateStr->" + formateStr);
SimpleDateFormat formate = new SimpleDateFormat(formateStr);
formate.setLenient(false);
Date result = null;
try {
result = formate.parse(time);
} catch (ParseException e) {
}
return result;
}
public static String repeat(String s,int counts) {
int len = s.length();
StringBuilder builder = new StringBuilder(len * counts);
for(int i=0; i<counts; i++){
builder.append(s);
}
return builder.toString();
}
测试:
public static void main(String[] args) {
String s = "2014 9/23:7";
SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd-HH");
Date d = convertStringToDate(s);
if(d != null) {
System.out.println(formate.format(d));
} else {
System.out.println(d);
}
}
-----输出
2014 9/23:7
2014 9/23:7
formateStr->yyyy M/dd:H
2014-09-23-07
-----
String s = "2014-9/23-7";
---输出
2014-09-23-07
String s = "2014-9/23-7";
---输出
2014-09-23-07
String s = "2014-9/31-7";
---输出
null
String s = "2014-9-ss-7";
---输出
null
其他自己去试吧。