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

时间:2018-04-26 10:55:41

标签: swift date nsdate

我正在处理日期和时间,我会记录登录日志并注销。对于例如登录时间是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小时。任何人都会这样做。

非常感谢帮助。

2 个答案:

答案 0 :(得分:3)

计算登录的总时间。

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

用于打印总登录时间的扩展名,以小时为单位:分钟:秒。

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

答案 1 :(得分:0)

请尝试以下代码,希望它能为您提供帮助。

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
    }