我喜欢使用扩展,使代码更可读。这里有一些NSDate扩展,可以帮助清理你的代码,使其易于理解。我把它放在sharedCode.swift文件中:
原文链接:https://www.f2er.com/swift/321756.htmlextension NSDate { func isGreaterThanDate(dateToCompare: NSDate) -> Bool { //Declare Variables var isGreater = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending { isGreater = true } //Return Result return isGreater } func isLessThanDate(dateToCompare: NSDate) -> Bool { //Declare Variables var isLess = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending { isLess = true } //Return Result return isLess } func equalToDate(dateToCompare: NSDate) -> Bool { //Declare Variables var isEqualTo = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedSame { isEqualTo = true } //Return Result return isEqualTo } func addDays(daysToAdd: Int) -> NSDate { let secondsInDays: NSTimeInterval = Double(daysToAdd) * 60 * 60 * 24 let dateWithDaysAdded: NSDate = self.dateByAddingTimeInterval(secondsInDays) //Return Result return dateWithDaysAdded } func addHours(hoursToAdd: Int) -> NSDate { let secondsInHours: NSTimeInterval = Double(hoursToAdd) * 60 * 60 let dateWithHoursAdded: NSDate = self.dateByAddingTimeInterval(secondsInHours) //Return Result return dateWithHoursAdded } }
现在如果你可以这样做:
//Get Current Date/Time var currentDateTime = NSDate() //Get Reminder Date (which is Due date minus 7 days lets say) var reminderDate = dueDate.addDays(-7) //Check if reminderDate is Greater than Right now if(reminderDate.isGreaterThanDate(currentDateTime)) { //Do Something... }