Check the date format of the string if it matches the required format or not.

I have the same question I asked here in Java, is this possible quickly?

func stringToDate(str: String) -> Date{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" //check validation of str return date } 
+6
source share
4 answers

Just like Java , check that it is processed correctly

 let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss" let someDate = "string date" if dateFormatterGet.date(from: someDate!) != nil { } else { // invalid format } 
+9
source

For Swift 4, the syntax has changed a bit:

  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 ie date return true } else { // Invalid date return false } } 
+7
source

in 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 } 
0
source

Swift 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 } 
0
source

Source: https://habr.com/ru/post/1265121/


All Articles