我试图将字符串日期(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")
}
这里有一个函数,可以将给定的字符串转换为日期,并将其与给定的日期(默认为今天(进行比较。通过使用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)
}
问题是日期是按字典顺序排列的。即使是数字,年份也应该在字符串中的月份之前,以便您能够比较日期字符串。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 pastn"
} else if date.isInToday {
print("Date is today")
} else {
print("Date is future")
}
}