Reputation: 73
I am getting two date string in this format, "08:00:00" coming from server side as a starting slot or ending slot. I have to get the time of local timezone and then check if the current time lies in between the time interval which is coming from server. But I am unable to do the comparison.
func checkTime() -> Bool {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = TimeZone(identifier: "PKT")
let startingSlot = self.selectedArea.startingSlot! //UTC
let endingSlot = self.selectedArea.endingSlot! //UTC
let date = Date().description(with: Locale.current)
let current = date.split(separator: " ")
let currentD:String = String(current[5])
let date1: Date = dateFormatter.date(from: startingSlot)!
let date2: Date = dateFormatter.date(from: endingSlot)!
let currentdate:Date = dateFormatter.date(from: currentD)!
print(date1)
print(date2)
print(current)
if(currentdate >= date1 && currentdate <= date2) {
return true
} else {
return false
}
}
I expect to get true if the current date time lies in between the date1 and date2.
Upvotes: 0
Views: 2684
Reputation: 3588
Compare the time by ignoring the date component -
func checkTime() -> Bool {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "PKT")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let startingSlot = "2000-01-01 08:00:00" //UTC
let endingSlot = "2000-01-01 23:00:00" //UTC
let date = Date()
let date1: Date = dateFormatter.date(from: startingSlot)!
let date2: Date = dateFormatter.date(from: endingSlot)!
let currentTime = 60*Calendar.current.component(.hour, from: date) + Calendar.current.component(.minute, from: date) + (Calendar.current.component(.second, from: date)/60) // in minutes
let time1 = 60*Calendar.current.component(.hour, from: date1) + Calendar.current.component(.minute, from: date1) + (Calendar.current.component(.second, from: date1)/60) // in minutes
let time2 = 60*Calendar.current.component(.hour, from: date2) + Calendar.current.component(.minute, from: date2) + (Calendar.current.component(.second, from: date1)/60) // in minutes
print(currentTime)
print(time1)
print(time2)
if(currentTime >= time1 && currentTime <= time2) {
return true
} else {
return false
}
}
Output-
1121
510
1410
true
Upvotes: 2