2017-09-27 56 views
-3

我想知道如何計算登錄時間和登出時間之間的差異,例如:登錄時間:上午8:00和登出時間:下午5:00,而我應該在總時間內得到9小時。iOS Swift - 計算兩次之差

這是被保存到火力

 // Set the time 
    let timeFormatter = DateFormatter() 
    timeFormatter.dateStyle = .none 
    timeFormatter.timeStyle = .short 
    timeFormatter.amSymbol = "AM" 
    timeFormatter.pmSymbol = "PM" 

    let timeString = timeFormatter.string(from: date) 
+1

可能的重複[使用swift 3和xcode 8在兩週內和兩天之間的差異](https://stackoverflow.com/questions/42294864/difference-between-2-dates-in-weeks-and-days -using-swift-3-and-xcode-8) – aksh1t

+1

重複的https://stackoverflow.com/a/42017851/2303865 –

+1

@LeoDabus,對不起。感謝提醒。祝你有美好的一天! – TSM

回答

1

在登錄......

在註銷
let loginTime = Date() 
    UserDefaults.standard.set(loginTime, forKey: "loginTime") 

則...

let loginTime = UserDefaults.standard.object(forKey: "loginTime") as? Date ?? Date() 
    let loginInterval = -loginTime.timeIntervalSinceNow 

    let formatter = DateComponentsFormatter() 
    formatter.unitsStyle = .full 
    formatter.includesApproximationPhrase = false 
    formatter.includesTimeRemainingPhrase = false 
    formatter.allowedUnits = [.hour, .minute] 

    // Use the configured formatter to generate the string. 
    let userLoginTimeString = formatter.string(from: loginInterval) ?? "" 
    print("user was logged in for \(userLoginTimeString)") 

享受!

+0

感謝您的回覆@ekscrypto。我也會試試這個。祝你今天愉快! – TSM

1

編輯時間格式:Found duplicate question

從登錄(loginTime)和註銷創建Date對象(link to question)(logoutTime)倍,然後像這樣使用它們:

let components = Calendar.current.dateComponents([.hour, .minute], from: loginTime, to: logoutTime) 

// To get the hours 
print(components.hour) 
// To get the minutes 
print(components.minute) 
+0

感謝您的回覆,@ aksh1t。我會試試這個。 – TSM

+0

很好的解決方案,有時間更新我的手動計算:D – ekscrypto