Add this code to your project and comparing dates is easier than ever
扩展NSDATE
//swift 3.0.2
extension NSDate { func isGreaterThanDate(dateToCompare : NSDate) -> Bool { var isGreater = false if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending { isGreater = true } return isGreater } func isLessThanDate(dateToCompare : NSDate) -> Bool { var isLess = false if self.compare(dateToCompare as Date) == ComparisonResult.orderedAscending { isLess = true } return isLess } func addDays(daysToAdd : Int) -> NSDate { let secondsInDays : TimeInterval = Double(daysToAdd) * 60 * 60 * 24 let dateWithDaysAdded : NSDate = self.addingTimeInterval(secondsInDays) return dateWithDaysAdded } func addHours(hoursToAdd : Int) -> NSDate { let secondsInHours : TimeInterval = Double(hoursToAdd) * 60 * 60 let dateWithHoursAdded : NSDate = self.addingTimeInterval(secondsInHours) return dateWithHoursAdded } }
t’s easy to use. Here’s a couple of examples
在.SWIFT调用就行了,EASY的很!
var today = NSDate() var oneHourFromNow = today.addHours(1) if today.isGreaterThanDate(oneHourFromNow) { println("Something is terrebly wrong.") } var aWeekFromNow = today.addDays(7)
原文链接:http://myxcode.net/2015/08/30/comparing-dates-in-swift/