计算当前时间和旧时间之间的时间 Swift

Calculate time between Current Time and Old Time Swift

我正在处理日期和时间,我在其中记录了登录和注销的日志。例如登录时间为 12:45,注销时间为 1:45,因此需要检查用户在线的总小时数。我有时间,下面是我试图通过添加来检查最大小时数的代码,但我没有得到我需要的输出。

//Current time
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .none
outTimeString = formatter.string(from: currentDateTime) as NSString

//LoggedIn Time
inTimeString = "12:49:50"
let inFormatter = DateFormatter()
inFormatter.dateFormat = "HH:mm:ss"

let outFormatter = DateFormatter()
outFormatter.dateFormat = "hh:mm"

let inTime = inTimeString
let date = inFormatter.date(from: inTime)!
let inStr = outFormatter.string(from: date)
print(inStr)->12:49:50

let outTime = outTimeString
let outDate = inFormatter.date(from: outTime as String)!
let outStr = outFormatter.string(from: outDate)
print(outStr)->16:10:15

//Adding 4 hour to logged in timw
let calendar = NSCalendar.current
let finaldate = date.addingTimeInterval(-4 * 60.0 * 60.0)
print(finaldate)->2000-01-01 03:19:50 +0000

问题是当登录时间加上 4 小时时我的输出错误。

我需要总登录时间或在原始登录时间的基础上增加 4 小时。任何一个都行。

非常感谢您的帮助。

试试下面的代码,希望对你有帮助。

func findIntervalBtwToDate(startingDate: String, endingDate : String) -> TimeInterval {
        var interval = 0.0
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss"
        dateFormatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
        guard let endDate = dateFormatter.date(from: endingDate), let startDate = dateFormatter.date(from: startingDate) else { return interval }
        interval = endDate.timeIntervalSince(startDate)
        return interval
    }

正在计算总登录时间。

var totalTimeLoggedIn: TimeInterval = 3600 // 1 hour

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"

guard
    let loginTimeDate = dateFormatter.date(from: "26-04-2018 12:00:00"),
    let logoutTimeDate = dateFormatter.date(from: "26-04-2018 13:00:00")
else {
    return
}

let timeLoggedIn = logoutTimeDate.timeIntervalSince(loginTimeDate)
totalTimeLoggedIn += timeLoggedIn

print("totalTimeLoggedIn: \(totalTimeLoggedIn.stringValue())") // totalTimeLoggedIn: 02:00:00

用于在 hours:minutes:seconds 中打印总登录时间的扩展。

extension TimeInterval {

    /// Returns the time interval into a string value in hours:minutes:seconds (e.g. 09:15:34)
    func stringValue(removeHoursIfEmpty:Bool = true) -> String {
        if(self.isNaN){
            return "00:00"
        }

        var value = self

        if value < 0 {
            value = 0
        }

        let hours:Int = Int(value / 3600)
        let minutes:Int = Int((value.truncatingRemainder(dividingBy: 3600)) / 60)
        let seconds:Int = Int(value.truncatingRemainder(dividingBy: 60))

        if (hours > 0 || removeHoursIfEmpty == false){
            return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
        } else {
            return String(format: "%02d:%02d", minutes, seconds)
        }
    }
}