import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
/**
* 尝试解析日期字符串为Date对象。
*
* @param dateString 要解析的日期字符串
* @return 成功解析时返回Date对象,解析失败时返回null
*/
public static Date parseStringToDate(String dateString) {
// 定义可能的日期格式
String[] formats = {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm:ss",
"yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss",
"dd-MM-yyyy",
"dd/MM/yyyy",
"dd/MM/yyyy HH:mm:ss",
"MM-dd-yyyy",
"MM/dd/yyyy",
"MM/dd/yyyy HH:mm:ss",
"yyyyMMdd",
"yyyyMMdd HHmmss",
"EEE, dd MMM yyyy HH:mm:ss zzz", // RFC1123
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
};
for (String format : formats) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.parse(dateString);
} catch (ParseException e) {
// 当前格式无法解析,尝试下一个格式
}
}
// 所有格式都尝试过了,仍然无法解析,返回null
return null;
}
public static void main(String[] args) {
String dateString1 = "2022-01-28";
String dateString2 = "2022-01-28 12:34:56";
String dateString3 = "28/01/2022";
// 尝试解析日期字符串
Date parsedDate =
解析时间字符串通用工具类
于 2024-01-28 16:57:40 首次发布