2016-02-01 79 views
0

我有一個Swift模型NSDate字段名爲expirationDate,我想根據當前日期計算剩餘到期之前。Swift:NSDate減去NSDate小時

有沒有一種簡單的方法來做到這一點與現有的NSDate功能?

回答

2

現在不能檢查,但應該類似

expirationDate.timeIntervalSinceNow/3600 
+0

這是一個比我更好的答案,我完全在T間隔imeIntervalSince現在甚至是一件事情。您的答案在REPL中無需修改即可使用。 – Undo

1

只要找到秒(NSTimeInterval)兩個日期之間通過60 * 60 = 3600號( '現在' 和到期日期)和除法:

let secondsUntilExpiration = expirationDate.timeIntervalSinceDate(NSDate()); 

let hoursUntilExpiration = secondsUntilExpiration/3600 

例如:

7> let now = NSDate() 
now: NSDate = 2016-02-01 03:44:06 UTC 
    8> let expirationDate = now.dateByAddingTimeInterval(60*60*10) // ten hours from now 
expirationDate: NSDate = 2016-02-01 13:44:06 UTC 
    9> let secondsUntilExpiration = expirationDate.timeIntervalSinceDate(NSDate()); 
secondsUntilExpiration: NSTimeInterval = 35991.422316968441 
10> let hoursUntilExpiration = secondsUntilExpiration/3600 
hoursUntilExpiration: Double = 9.9976173102690122 
// Slightly less than the 10 hours above because of the time it took me to type.