Swift - 日期字符串比较

Swift - Date String Compare

我正在尝试将字符串日期 (StringDate = "MMM dd, yyyy") 与今天的日期进行比较,但如果月份不同,代码并不总是有效。有什么想法吗?

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

问题是日期是按字典顺序排列的。即使它是数字,年份也应该在字符串中的月份之前,以便您能够比较日期字符串。 Swift 中的日期是可比较的,如果你想做一个时间不敏感的比较,你只需要使用中午时间。所以你需要的是解析你的日期字符串,获取中午并将其与今天的中午进行比较。

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

游乐场测试:

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

这是一个将给定字符串转换为日期并将其与给定数据(今天的默认值)进行比较的函数。通过使用 startOfDay(for:) 时间在比较中被忽略

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