Search code examples
swiftswift3nsdateformatter

Check the date format of string if it's according to required format or not


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
}

Solution

  • 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
    }