10

I have the same question asked here in Java, is it possible in swift?

func stringToDate(str: String) -> Date{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"

    //check validation of str 

    return date
}
Community
  • 1
  • 1
Marry G
  • 377
  • 1
  • 3
  • 16

4 Answers4

22

Just same like Java, check if it can parse properly

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd hh:mm:ss"
let someDate = "string date"

if dateFormatterGet.date(from: someDate) != nil {
    // valid format
} else {
    // invalid format
}
Gurtej Singh
  • 225
  • 1
  • 9
Đào Minh Hạt
  • 2,742
  • 16
  • 20
8

For Swift 4 the syntax have 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 i.e date
        return true
    } else {
        // Invalid date
        return false
    }
}
Ollikas
  • 199
  • 1
  • 3
  • 14
0

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

}
Marry G
  • 377
  • 1
  • 3
  • 16
0

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
}
Kingsley Mitchell
  • 2,412
  • 2
  • 18
  • 25