2017-09-27 83 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