多种格式的日期时间转换兼容

说明

有的时候可能会遇到各种格式的时间表现形式,比如:2018-03-12 12:05:34、2018-03-12 12:05、2018-3-12 12:5:34、2018-03-12、2018/3/12 12:5:34、2018年03月12日 13时05分34秒等等这些形式的表现,如果需要对这种格式不确定的输入时间进行统一转换,肯定是要考虑到不同的形式进行不同的转换的,然后统一输出一种格式的表现形式,比如统一为这种表现形式:2018-03-12 12:05:34。

工具类

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
package com.example.toby.myapplication;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.regex.Pattern;

/**
* author : toby
* e-mail : 13128826083@163.com
* time : 2018/2/2
* desc :
*/

public class DateFormatUtil {

/**
* 格式化时间
*
* @param dateStr
* @return
*/
public static String dateRegFormat(String dateStr) {
HashMap<String, String> dateRegFormat = new HashMap<>();
// 2014年3月12日 13时5分34秒,2014-03-12 12:05:34,2014/3/12 12:5:34
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");

// 2014-03-12 12:05,2014-3-12 12:5
dateRegFormat.put("^\\d{4}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D*$", "yyyy-MM-dd-HH-mm");

// 2014-03-12
dateRegFormat.put("^\\d{4}\\D+\\d{1,2}\\D+\\d{1,2}$", "yyyy-MM-dd");

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));
dateReplace = dateStr.replaceAll("\\D+", "-");
strSuccess = formatter1.format(formatter2.parse(dateReplace));
break;
}
}
} catch (Exception e) {
System.err.println("---------日期格式无效-----------" + dateStr);
throw new Exception("日期格式无效");
} finally {
return strSuccess;
}
}

}

测试结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private void testDateFormat() {
String[] dateStrArray = new String[]{
"2018-03-12 12:05:34",
"2018-03-12 12:05",
"2018-3-12 12:5:34",
"2018-3-12 12:5",
"2018-3-12",
"2018-03-12",
"2018/03/12 12:05:34",
"2018/3/12 12:5:34",
"2018/03/12 12:05",
"2018/3/12 12:5",
"2018/03/12",
"2018年3月12日 13时5分34秒",
"2018年3月12日 13时5分",
"2018年03月12日 13时05分34秒"
};
for (int i = 0; i < dateStrArray.length; i++) {
Log.d("----index---->" + i, DateFormatUtil.dateRegFormat(dateStrArray[i]));
}
}