使用Swift的NSDate比较
发布时间:2020-12-14 06:18:28 所属栏目:百科 来源:网络整理
导读:我正在开发一个应用程序,需要检查到期日作业。我想知道到期日是否在下周内,如果是,然后执行操作。 我可以找到的大多数文档是在Objective-C,我不知道如何在Swift中做。 谢谢您的帮助!! 我喜欢使用扩展,使代码更可读。这里有一些NSDate扩展,可以帮助清
我正在开发一个应用程序,需要检查到期日作业。我想知道到期日是否在下周内,如果是,然后执行操作。
我可以找到的大多数文档是在Objective-C,我不知道如何在Swift中做。 谢谢您的帮助!!
我喜欢使用扩展,使代码更可读。这里有一些NSDate扩展,可以帮助清理你的代码,使其易于理解。我把它放在sharedCode.swift文件中:
extension 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... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |