我在Java中问过同样的问题here, 它有可能在swift?
func stringToDate(str: String) -> Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
//check validation of str
return date
}
答案 0 :(得分:8)
与Java
一样,检查它是否可以正确解析
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
let someDate = "string date"
if dateFormatterGet.date(from: someDate!) != nil {
} else {
// invalid format
}
答案 1 :(得分:5)
对于Swift 4,语法有所改变:
func isValidDate(dateString: String) -> Bool {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
if let _ = dateFormatterGet.date(from: dateString) {
//date parsing succeeded, if you need to do additional logic, replace _ with some variable name i.e date
return true
} else {
// Invalid date
return false
}
}
答案 2 :(得分:0)
在swift3中:
func stringToDate(str: String) -> Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
guard let date = dateFormatter.date(from: str){
return Date()
}
return date
}
答案 3 :(得分:0)
雨燕5
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
let someDate = "string date"
if dateFormatterGet.date(from: someDate!) != nil {
} else {
// invalid format
}