kotlin 以"yyyy-MM-dd HH:mm:ss"的格式 校验一个字符串是否为正确的时间 比如“2001-2-30 10:00:00“是否为正确的
时间: 2024-02-01 20:13:16 浏览: 21
可以使用`java.time.format.DateTimeFormatter`类来进行校验,具体实现如下:
```kotlin
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
fun validateDateTime(dateTimeString: String): Boolean {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
try {
// 将字符串解析为 LocalDateTime
val dateTime = LocalDateTime.parse(dateTimeString, formatter)
// 校验是否符合格式
val formattedString = dateTime.format(formatter)
return formattedString == dateTimeString
} catch (e: DateTimeParseException) {
return false
}
}
```
其中,`DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")`用于创建一个格式化器,`LocalDateTime.parse(dateTimeString, formatter)`用于将字符串解析为`LocalDateTime`对象,`dateTime.format(formatter)`用于将`LocalDateTime`对象格式化为字符串,最后比较格式化后的字符串和原始字符串是否相等,如果相等,则说明原始字符串符合格式要求,返回`true`,否则返回`false`。