package
com.st.test;
import
java.text.DateFormat;
import
java.text.SimpleDateFormat;
import
java.util.Date;
import
java.util.HashMap;
import
java.util.regex.Pattern;
public
class
DateFormatUtil {
@SuppressWarnings
(
"finally"
)
public
static
String FormatDate(String dateStr){
HashMap<String,
String> 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"
);
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;
}
}
public
static
void
main(String[] args) {
String[]
dateStrArray=
new
String[]{
"2014-03-12
12:05:34"
,
"2014-03-12
12:05"
,
"2014-03-12
12"
,
"2014-03-12"
,
"2014-03"
,
"2014"
,
"20140312120534"
,
"2014/03/12
12:05:34"
,
"2014/3/12
12:5:34"
,
"2014年3月12日
13时5分34秒"
,
"201403121205"
,
"1234567890"
,
"20140312"
,
"201403"
,
"2000
13 33 13 13 13"
,
"30.12.2013"
,
"12.21.2013"
,
"21.1"
,
"13:05:34"
,
"12:05"
,
"14.1.8"
,
"14.10.18"
};
for
(
int
i=
0
;i<dateStrArray.length;i++){
System.out.println(dateStrArray[i]
+
"------------------------------"
.substring(
1
,
30
-dateStrArray[i].length())+
FormatDate(dateStrArray[i]));
}
}
}