日期格式问题:如何让isValidDateString方法拒绝短年份输入?
问题描述
现有用于验证日期字符串的Java方法:
private boolean isValidDateString(String value){ // value = "01.02.22" if(value != null){ SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); try{ Date parse = sdf.parse((String) value); }catch (Exception e){ LOG.debug("Invalid date string : "+value); return false; } } return true; }
当输入"01.01.22"这类短年份字符串时,该方法返回true,但需要让这类输入返回false,以提示用户格式应为dd.MM.yyyy,如何实现?
解决方案
方法1:改进SimpleDateFormat实现
SimpleDateFormat默认会自动补全年份(比如22会被解析为2022),要严格限制年份为4位,需做以下调整:
- 调用
setLenient(false)关闭宽松解析,避免非法格式被兼容 - 提前检查字符串的长度和分隔符位置,确保结构符合
dd.MM.yyyy - 验证解析后的年份与输入的4位年份完全一致,避免特殊场景的误判
修改后的代码:
private boolean isValidDateString(String value){ if(value == null){ return false; } // 先校验格式结构:长度为10,第3、6位是分隔符 if(value.length() != 10 || value.charAt(2) != '.' || value.charAt(5) != '.'){ LOG.debug("Invalid date string format : "+value); return false; } SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); sdf.setLenient(false); // 开启严格解析模式 try{ Date parsedDate = sdf.parse(value); // 校验解析后的年份与输入的4位年份一致 String inputYear = value.substring(6); String parsedYear = new SimpleDateFormat("yyyy").format(parsedDate); if(!inputYear.equals(parsedYear)){ LOG.debug("Invalid 4-digit year : "+value); return false; } return true; }catch (Exception e){ LOG.debug("Invalid date string : "+value); return false; } }
方法2:使用Java 8+的DateTimeFormatter(推荐)
Java 8及以后的java.time包提供了线程安全、更可靠的日期处理API,DateTimeFormatter支持严格解析模式,可直接限制年份为4位:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.format.ResolverStyle; private boolean isValidDateString(String value){ if(value == null){ return false; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") .withResolverStyle(ResolverStyle.STRICT); // 严格匹配格式规则 try{ LocalDate.parse(value, formatter); return true; }catch (DateTimeParseException e){ LOG.debug("Invalid date string : "+value); return false; } }
此方式下,"01.01.22"会直接抛出DateTimeParseException,方法返回false,完全符合需求。
内容的提问来源于stack exchange,提问作者Tusker
相关产品推荐
相关产品推荐

