I am new in swift I search this questing and also got answer but not worked for me. 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. 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. 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. 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
You have to differentiate date and duration. Today is 8/4/2020, you can't compare it with duration as 1 hour, 2 hours.
if your anotherdate
is two hours, why you don't compare it as: 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{
}