String dateString = "5/26/22";
Date date = null;
if(dateString.contains("/")){
String temp = dateString.replaceAll("/", "");
String temp2 = dateString.replaceFirst("\\d+/\\d+/", "");
if(3 < temp.length() && temp.length() < 7 && temp2.length()==2) {
//兼容MM/dd/yy格式,如5/26/22
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
date = dateFormat.parse(dateString);
return date;
}else if (5 < temp.length() && temp.length() < 9 && temp2.length()==4) {
//兼容MM/dd/yyyy格式,如5/26/2022
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
date = dateFormat.parse(dateString);
return date;
}
}
日期精准匹配MM/dd/yy,MM/dd/yyyy
于 2022-04-27 10:03:49 首次发布
这段代码主要处理日期字符串,检查并尝试将其转换为两种可能的格式:MM/dd/yy 和 MM/dd/yyyy。它首先检查字符串是否包含斜杠,然后分别用正则表达式处理不同的日期格式,最后使用SimpleDateFormat进行解析。
109

被折叠的 条评论
为什么被折叠?



