在开发的过程中,客户要求有的日期需要用户手动输入和日期选择器共同存在,日期选择器的我们当然不需要去校验,手动输入的就需要校验.
总结了一下开发过程中的算法,简化后更加简洁有效,代码如下:
func effectiveDate(year:Int,month:Int,day:Int)->Bool{
if year <= 0{return false}
if month < 1 || month > 12{return false}
var months = [31,0,31,30,31,30,31,31,30,31,30,31]
if (year%4 == 0 && year%100 != 0) || year%400 == 0{
months[1] = 29
}else{
months[1]=28
}
return (day>=1)&&(day<=months[month-1])
}
可以在playground进行验证
如果你觉得按位截取比较麻烦的话,可以把截取的方法写在effectiveDate里,这样拿到8位日期就可以直接验证合法性了
字符串截取:
let year = (text as NSString).substringWithRange(NSMakeRange(0, 4))
let mouth = (text as NSString).substringWithRange(NSMakeRange(4, 2))
let day = (text as NSString).substringWithRange(NSMakeRange(6, 2))
转载请注明原文地址: https://ju.6miu.com/read-677824.html