简体   繁体   中英

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")
}

The issue there is that the date is ordered lexicographically. Even if it were numbers the year should precede the month in your string for you to be able to compare your date strings. Date in Swift are comparable and if you want to do a time insensitive comparison all you need is to use noon time. So what you need is to parse your date string, get noon and compare it to today's noon.

extension Date {
    static var noon: Date { Date().noon }
    var noon: Date { Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)! }
    var isInToday: Bool { Calendar.current.isDateInToday(self) }
    var isInThePast: Bool { noon < .noon }
    var isInTheFuture: Bool { noon > .noon }
}

Playground testing:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMM dd, yyyy"
let stringDate = "Oct 20, 2020"
if let date = dateFormatter.date(from: stringDate) {
    if date.isInThePast {
        print("Date is past")  // "Date is past\n"
    } else if date.isInToday {
        print("Date is today")
    } else {
        print("Date is future")
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM