时间比较迅速

题:

我需要比较2次 – 当前时间和一个。 如果设定的时间是未来的时间,则查明在未来的时间内剩余多less分钟。

其他信息:

我目前正在使用

let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date) let hour = components.hour let minutes = components.minute 

我从另一个关于如何以Int格式获取当前时间的答案偷了。 然后我把未来的时间分成小时(Int)和分钟(Int),然后比较这些……但是当你超过小时障碍时,这会变得很奇怪。

你有比较function比较2 NSDate知道哪一个是最近的。 它返回NSCompareResults

 enum NSComparisonResult : Int { case OrderedAscending case OrderedSame case OrderedDescending } 

从2 NSDate获得距离(秒),你有.timeIntervalSinceDate()。 那么,你知道如何转换为分钟,小时,…

 let date1 : NSDate = ... let date2 : NSDate = ... let compareResult = date1.compare(date2) let interval = date1.timeIntervalSinceDate(date2) 

只是添加到@ tyt_g207的答案,我发现了比较方法,但没有findNSComparisonResult.OrderedDescending和其他。 我使用类似下面的修改来检查到今天的date到期date

 let date1 : NSDate = expirationDate let date2 : NSDate = NSDate() //initialized by default with the current date let compareResult = date1.compare(date2) if compareResult == NSComparisonResult.OrderedDescending { println("\(date1) is later than \(date2)") } let interval = date1.timeIntervalSinceDate(date2) 
  let dateComparisionResult: NSComparisonResult = currentDate.compare("Your Date") if dateComparisionResult == NSComparisonResult.OrderedAscending { // Current date is smaller than end date. } else if dateComparisionResult == NSComparisonResult.OrderedDescending { // Current date is greater than end date. } else if dateComparisionResult == NSComparisonResult.OrderedSame { // Current date and end date are same. } 

使用date的timeIntervalSinceDate进一步date并通过较早的date作为参数,这会给时间差