2017-04-26 77 views
1

我確定當前時間迅速與此代碼時間戳斯威夫特

let currentDate = Date().timeIntervalSince1970 * 1000 

結果看起來像

1493199752604.24 

所獲得的數值是以毫秒爲單位對不對?值是什麼.

我需要確定兩個這樣的日期之間的差異是否等於或大於2小時。

if (currentDate - oldDate >= 7200000){ 
// do something 
} 

這段代碼正確嗎?

+0

VAR時間戳:字符串{ 返回 「\(的NSDate()timeIntervalSince1970 * 1000)」 } 這樣稱呼它就像時間戳 –

+3

這個神祕的*「'。」裏面的值「*」表示'timeIntervalSince1970'返回一個*浮點數*(你可以從文檔中看到,或者通過命令單擊屬性名稱在Xcode中)。 –

+0

TimeInterval以秒爲單位,在'.'之後,您已經得到第二部分 – Kubba

回答

0

嘗試使用Swift的更多優惠。嘗試使用dateComponents以小時爲單位獲取差值。

let calendar = NSCalendar.current 

let hours = calendar.dateComponents([.hour], from: Date(), to: Date()) 
+0

讓calendar = NSCalendar.current 讓hours = calendar.dateComponents([。hour],from:Date(),到:oldDate)這將以小時計算當前日期和oldDate之間的差異?例如,如果差異是兩天,結果將是48? –

+0

@ J.Doe是的,你是對的 –

0

是的,它工作正常。結帳這個例子 爲差超過2小時

let currentDate = Date().timeIntervalSince1970*1000 
let calendar = NSCalendar.current 
let yesteraysDate = calendar.date(byAdding: .day, value: -1, to: Date()) 
let oldDate = yesteraysDate!.timeIntervalSince1970*1000 
if (currentDate - oldDate >= 7200000){ 
    print("greater or equal than two hour") //"greater or equal than two hour" 
} else { 
    print("smaller than two hour") 
} 

如果差小於2小時

let currentDate = Date().timeIntervalSince1970*1000 
let calendar = NSCalendar.current 
let yesteraysDate = calendar.date(byAdding: .hour, value: -1, to: Date()) 
let oldDate = yesteraysDate!.timeIntervalSince1970*1000 
if (currentDate - oldDate >= 7200000){ 
    print("greater or equal than two hour") 
} else { 
    print("smaller than two hour") //"smaller than two hour"" 
}