Search code examples
swiftdatedatetimecomparedateformatter

Swift - Date String Compare


I am trying to compare a string date (StringDate = "MMM dd, yyyy") to today's date but if the months are different the code does not always work. Any thoughts?

let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
dateFormatter.dateFormat = "MMM dd, yyyy"       
let dateWithTime = Date()
let dateFormatter2 = DateFormatter()
dateFormatter2.dateStyle = .medium
var currentDay = dateFormatter2.string(from: dateWithTime) 
if currentDay.count != 12 {
    currentDay.insert("0", at: currentDay.index(currentDay.startIndex, offsetBy: 4))
}       
if stringDate < currentDay {
    print("Date is past")
}

Solution

  • Here is a function that converts the given string to a date and compares it to the given dat (default today). By using startOfDay(for:) time is ignored in the comparison

    func before(_ string: String, date: Date = Date()) -> Bool? {
        let locale = Locale(identifier: "en_US_POSIX")
    
        let dateFormatter = DateFormatter()
        dateFormatter.locale = locale
        dateFormatter.dateFormat = "MMM dd, yyyy"
    
        guard let inDate = dateFormatter.date(from: string) else {
            return nil
        }
        var calendar = Calendar.current
        calendar.locale = locale
        return inDate < calendar.startOfDay(for: date)
    }