[英]How to compare two time string check if string2 is grater then first string in swift
I am new in swift I search this questing and also got answer but not worked for me.我是 swift 的新人,我搜索了这个问题,也得到了答案,但对我没有用。 Sorry for asking this again.
很抱歉再次问这个问题。 My question is how to compare two time string.
我的问题是如何比较两个时间字符串。 I am using this code.
我正在使用这段代码。
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let result = formatter.string(from: date)
print(result)
var totalTimeLoggedIn = TimeInterval() // 1 hour
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let loginTimeDate = dateFormatter.date(from: lblWorkStarted.text ?? "")!
let logoutTimeDate = dateFormatter.date(from: result)!
let timeLoggedIn = logoutTimeDate.timeIntervalSince(loginTimeDate)
totalTimeLoggedIn += timeLoggedIn
print("totalTimeLoggedIn: \(totalTimeLoggedIn.stringValue())")
let TotalTimeLoginString = totalTimeLoggedIn.stringValue()
let anotherdate = "02:00:00"
if anotherdate < TotalTimeLoginString{
print("True")
}else{
}
lblWorkStarted.text is the current date and time. lblWorkStarted.text 是当前日期和时间。 I am facing problem is that if TotalTimeLoginString is "10:15" some value like this then condition is not working properly and if TotalTimeLoginString is "03:12:11" some value like this then it is working properly.
我面临的问题是,如果 TotalTimeLoginString 是“10:15”这样的某个值,则条件无法正常工作,如果 TotalTimeLoginString 是“03:12:11”这样的某个值,则它可以正常工作。 My problem is if I did not get hour then condition is not working.
我的问题是,如果我没有得到小时,那么条件就不起作用。 Thanks in Advance!
提前致谢!
you have some mistakes here:你在这里有一些错误:
You should create DateFormatter() again.您应该再次创建 DateFormatter()。 It's heavy operation as https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW10
这是繁重的操作https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW10
You have to differentiate date and duration.您必须区分日期和持续时间。 Today is 8/4/2020, you can't compare it with duration as 1 hour, 2 hours.
今天是 8/4/2020,你不能将它与持续时间作为 1 小时、2 小时进行比较。
if your anotherdate
is two hours, why you don't compare it as: 2 * 60 * 60 < totalTimeLoggedIn
?如果您的
anotherdate
是两个小时,为什么不将其比较为: 2 * 60 * 60 < totalTimeLoggedIn
?
let date = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let loginTimeDate = dateFormatter.date(from: lblWorkStarted.text?? ""). let timeLoggedIn = Date().timeIntervalSince(loginTimeDate) let anotherDate = 2 * 60 * 60 if anotherDate < timeLoggedIn { print("True") }else{ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.