我想知道如何计算登录时间和注销时间之间的差异,例如:登录时间:上午8:00和注销时间:下午5:00,我应该得到9小时作为总小时呈现。
这是保存到Firebase的时间格式

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

    let timeString = timeFormatter.string(from: date)

最佳答案

登录时。。。

    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)")

关于ios - iOS Swift-计算两次之间的差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46438227/

10-11 16:47