在需要将字符串转换为日期时,有时并不能完全固定输入的字符串格式,或者需要对其进行校验,比如excel导入功能等,而日期转换是需要特定格式的字符串输入的,这就需要我们提前对字符串进行校验和转化.
以下对一些常用格式的日期字符串进行了检查,并判断了年月日的数目是否正确,直接调用managerDate(str)即可,其中纯数字字符串必须是八位才符合条件,日期分割符为 ‘年’,‘月’,‘日’,’-’,’/’,’\’,’.’,’*'中的一个,需要补充可以对pattern1进行修改
public static String managerDate(String value){
String result = "";
String pattern1 = "^\\d{4}(年|-|/|\\.|\\\\|\\*)(0?[1-9]|1[0-2])(月|-|/|\\.|\\\\|\\*)((0?[1-9])|((1|2)[0-9])|30|31)(日|)$";
String pattern2 = "^\\d{4}(0?[1-9]|1[0-2])((0?[1-9])|((1|2)[0-9])|30|31)$";
Pattern r1 = Pattern.compile(pattern1);
Matcher m1 = r1.matcher(value);
Pattern r2 = Pattern.compile(pattern2);
Matcher m2 = r2.matcher(value);
if(m1.matches()){
result = value.replaceAll("(年|月|-|/|\\.|\\\\|\\*)","-");
result = result.replaceAll("日","");
}else if(m2.matches()){
if(value.length() != 8){
throw new ResultException("日期格式不正确,请检查!");
}
result = value.substring(0,4) + "-" + value.substring(4,6) + "-" + value.substring(6);
}else{
throw new ResultException("日期格式不正确,请检查!");
}
String[] dateArr = result.split("-");
int year = Integer.valueOf(dateArr[0]);
int month = Integer.valueOf(dateArr[1]);
int day = Integer.valueOf(dateArr[2]);
int[] monthLengths = new int[]{0, 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(isLeapYear(year)){
monthLengths[2] = 29;
}else{
monthLengths[2] = 28;
}
int monthLength = monthLengths[month];
if(day>monthLength){
throw new ResultException("日期格式不正确,请检查!");
}
result = year + "-" + ("0" + month).substring(("0" + month).length() - 2) + "-" + ("0" + day).substring(("0" + day).length() - 2);
return result;
}
private static boolean isLeapYear(int year){
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ;
}
注: 里面的抛出异常请替换为自己适合的方式;想要另外的格式可以修改最后的result拼接,也可以将其改为传入分隔符参数的方式增加其通用性(java小白,如果有其它更好的方法或者建议,欢迎评论)