简体   繁体   English

Swift - 日期字符串比较

[英]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.我正在尝试将字符串日期 (StringDate = "MMM dd, yyyy") 与今天的日期进行比较,但如果月份不同,则代码并不总是有效。 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. Swift 中的日期是可比较的,如果你想做一个时间不敏感的比较,你只需要使用中午时间。 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).这是一个将给定字符串转换为日期并将其与给定 dat(今天的默认值)进行比较的函数。 By using startOfDay(for:) time is ignored in the comparison通过使用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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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