我正在开发需要检查作业截止日期的应用程序。我想知道到期日期是否在下个星期之内,然后再执行一项操作。 我可以找到的大多数文档都在Objective-C中,但我不知道如何在Swift中完成。谢谢您的帮助!!
我喜欢使用扩展使代码更具可读性。以下是一些NSDate扩展,它们可以帮助清理代码并使其易于理解。我把它放在一个sharedCode.swift文件中:
extension NSDate { func isGreaterThanDate(dateToCompare: NSDate) -> Bool { //Declare Variables var isGreater = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending { isGreater = true } //Return Result return isGreater } func isLessThanDate(dateToCompare: NSDate) -> Bool { //Declare Variables var isLess = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedAscending { isLess = true } //Return Result return isLess } func equalToDate(dateToCompare: NSDate) -> Bool { //Declare Variables var isEqualTo = false //Compare Values if self.compare(dateToCompare as Date) == ComparisonResult.orderedSame { isEqualTo = true } //Return Result return isEqualTo } func addDays(daysToAdd: Int) -> NSDate { let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24 let dateWithDaysAdded: NSDate = self.addingTimeInterval(secondsInDays) //Return Result return dateWithDaysAdded } func addHours(hoursToAdd: Int) -> NSDate { let secondsInHours: TimeInterval = Double(hoursToAdd) * 60 * 60 let dateWithHoursAdded: NSDate = self.addingTimeInterval(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... }