校验前台传过来的yyyy-MM-dd格式的字符串是否是正常的日期以及格式是否正确?
时间: 2023-04-02 18:01:07 浏览: 138
您好,可以使用C语言中的时间库函数来判断传入的日期字符串是否是正常的日期以及格式是否正确。具体可以使用strptime函数将字符串转换为时间格式,如果转换成功则说明日期格式正确,否则说明格式不正确。同时,可以使用mktime函数将时间格式转换为时间戳,如果时间戳为-1,则说明日期不合法。
相关问题
校验前台传过来的yyyy-MM-dd格式的字符串是否是正常的日期以及格式是否正确,使用java实现,并生成代码
可以使用Java中的SimpleDateFormat类来校验日期格式是否正确,代码如下:
String dateStr = "2022-01-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
try {
Date date = sdf.parse(dateStr);
System.out.println("日期格式正确:" + date);
} catch (ParseException e) {
System.out.println("日期格式错误:" + dateStr);
}
其中,setLenient(false)表示严格校验日期格式,如果日期格式不正确,则会抛出ParseException异常。如果日期格式正确,则会将字符串转换成Date类型的对象。
你可以将上述代码封装成一个方法,用于校验前台传过来的日期字符串是否正确。
校验字符串是否属于yyyy-MM-dd格式的时间字符串
可以通过正则表达式来校验一个字符串是否属于yyyy-MM-dd格式的时间字符串,具体的正则表达式如下:
```java
String regex = "\\d{4}-\\d{2}-\\d{2}";
boolean isMatch = Pattern.matches(regex, str);
```
其中,str为待校验的字符串。如果返回的isMatch为true,则说明该字符串符合yyyy-MM-dd格式的时间字符串的要求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)