Gowtham M
Gowtham M

Reputation: 13

Date validation in Swift 3

How can I check whether an entered date is in dd:mm:yyyy format? If the user enters a wrong date, then it should display "invalid date".

Upvotes: 0

Views: 3625

Answers (1)

glyvox
glyvox

Reputation: 58069

You should use DateFormatter to check whether your string is valid by the format given to DateFormatter's dateFormat parameter.

let dateString = "31:12:2017"

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

if dateFormatter.date(from: dateString) != nil {
    print("date is valid")
} else {
    print("date is invalid")
}

Upvotes: 3

Related Questions