java中任意时间字符串的格式化提取,不管是-还是/,都可以提取为标准的 yyyy-MM-dd HH:mm:ss格式。
代码如下:
/**
* 任意包含时间的字符串格式,标准化提取为 yyyy-MM-dd HH:mm:ss的格式
*
* @param strDate
* @return 提取失败,返回null
*/
public static String String2DateString(String strDate) {
// 正则表达式用于匹配常见的时间格式
String regex = "(\\d{4}[-/]?((0[1-9]|1[012])[-/](0[1-9]|[12][0-9]|3[01]))|([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9])";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(strDate);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while (matcher.find()) {
String timeStr = matcher.group();
System.out.println("Found time: " + timeStr);
try {
// 尝试用不同的格式解析时间
Date date = null;
if (timeStr.contains(":")) { // 包含时分秒
if (timeStr.contains("-") || timeStr.contains("/")) {
// yyyy-MM-dd HH:mm:ss 或者 yyyy/MM/dd HH:mm:ss
inputFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
} else {
// HH:mm:ss
inputFormat.applyPattern("HH:mm:ss");
}
} else if (timeStr.contains("-") || timeStr.contains("/")) { // 只有日期
if (timeStr.contains("-")) {
// yyyy-MM-dd
inputFormat.applyPattern("yyyy-MM-dd");
} else {
// yyyy/MM/dd
inputFormat.applyPattern("yyyy/MM/dd");
}
}
date = inputFormat.parse(timeStr);
// 格式化为统一的输出格式
String formattedDate = outputFormat.format(date);
//System.out.println("Formatted: " + formattedDate);
return formattedDate;
} catch (ParseException e) {
//System.err.println("Unable to parse the time string: " + timeStr);
}
}
return null;
}