iOS Swift - 计算两次之间的差异

时间:2017-09-27 01:45:22

标签: ios swift time

我想知道如何计算登录时间和退出时间之间的差异,例如:登录时间:上午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)

2 个答案:

答案 0 :(得分:5)

修改: Found duplicate question

从登录(Date)创建loginTime个对象(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)

答案 1 :(得分:3)

登录时......

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