我正在尝试检查字符串是否包含24小时时间。这是我当前的代码:
func isMilTime(from string: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
if (dateFormatter.date(from: string) != nil) {
return true
}else{
return false
}
}
print(isMilTime(from: "9:2")) //true
当前,像“ 9:2”这样的单位时间返回为true。如何修改此设置以仅检测两位数的时间,例如“ 9:02”?
要仅检查我建议使用正则表达式解决方案的格式,它将返回true
该范围0:00 – 23:59
func isMilTime(from string: String) -> Bool {
return string.range(of: "^(2[0-3]|[01]?\\d):[0-5]\\d$", options: .regularExpression) != nil
}
print(isMilTime(from: "9:2")) //false
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句