赞
踩
- /**
- * 判断字符串是否为合法的日期格式
- * @param dateStr 待判断的字符串
- * @return
- */
- public static boolean isValidDate(String dateStr){
- //判断结果 默认为true
- boolean judgeresult=true;
- //1、首先使用SimpleDateFormat初步进行判断,过滤掉注入 yyyy-01-32 或yyyy-00-0x等格式
- //此处可根据实际需求进行调整,如需判断yyyy/MM/dd格式将参数改掉即可
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
- try{
- //增加强判断条件,否则 诸如2022-02-29也可判断出去
- format.setLenient(false);
- Date date =format.parse(dateStr);
- System.out.println(date);
- }catch(Exception e){
- judgeresult=false;
- }
- //由于上述方法只能验证正常的日期格式,像诸如 0001-01-01、11-01-01,10001-01-01等无法校验,此处再添加校验年费是否合法
- String yearStr=dateStr.split("-")[0];
- if(yearStr.startsWith("0")||yearStr.length()!=4){
- judgeresult=false;
- }
- return judgeresult;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。