Search code examples
swiftswiftdate

Compare two date - Swift


How can I convert string like (2019-11-02) without time to date format and get current Date device without time then compare with together?


Solution

  • You can convert the string to date using a dateFormatter then compare with the current date using an if statement

    import Foundation
    
    //convert string to date
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let myDate = dateFormatter.date(from: "2019-11-02")
    
    
    //convert today's date in the same formate
    
    let currentFormatter = DateFormatter()
    currentFormatter.dateStyle = .short
    currentFormatter.dateFormat = "yyyy-MM-dd"
    let today = currentFormatter.string(from: Date())
    let todayDate = dateFormatter.date(from: today)
    
    //Compare the two date's
    
    if myDate == todayDate {
        print("ok")
    }