gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:41:42 27 4
gpt4 key购买 nike

我正在处理日期和时间,我会在其中记录登录和注销的日志。例如登录时间为 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 小时。任何人都可以。

非常感谢您的帮助。

最佳答案

计算总登录时间。

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

关于swift - 计算当前时间和旧时间 Swift 之间的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50041196/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com