2014-06-19 83 views
10

問題:swift中的時間比較

我需要比較2次 - 當前時間和一個設置。如果設定的時間是未來的時間,則查明在未來的時間內剩餘多少分鐘。

其他信息:

我目前使用

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

這是我從另一個答案搶在SO如何得到詮釋格式的當前時間。然後我把未來的時間分成小時(Int)和分鐘(Int),然後比較這些......但當你超過小時障礙時,這會變得很奇怪。

+1

見... HTTP截止日期://stackoverflow.com/questions/5965044/how-to-compare-two-nsdates-這是更多最近的和對這個問題的第一個評論。 – Jack

回答

22

您有比較功能比較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) 
4

使用日期進一步日期timeIntervalSinceDate並通過更早的日期參數,這將給時差

10

只是補充以@ tyt_g207的答案,我找到了比較方法,但沒有找到NSComparisonResult.OrderedDescending和其他人。我用類似下面的修改,以覈對當天的日期

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) 
+0

這是全部在UTC?比較當地時間呢? –

5
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. 

    }