I am getting crash on checking the date:
func cehckForDate(date: String?) -> Int{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let fromDt = dateFormatter.date(from: date ?? "")
let curreentDate = Date()
let order = Calendar.current.compare(curreentDate , to: fromDt!, toGranularity: .day)
switch order {
case .orderedAscending:
return(2)
case .orderedDescending:
return(1)
case .orderedSame:
return(0)
}
return 0
}
My crash on here:
let order = Calendar.current.compare(curreentDate , to: fromDt!, toGranularity: .day)
I am getting nil
for fromDt
i am getting my date as 2018-08-16 15:04:17
Like @rmaddy said, the problem is your date format and your input - they don't match. hh
-> 12 hour format, HH
-> 24 hour format which is what you need. ( Refer the link at the bottom to check what you need to use for your input )
func checkForDate(date: String = "") -> Int{
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let validDateFound = dateFormatter.date(from: date) else {
print("Invalid date received. Please check if the date matches the date format - \(date)")
return -1 //Proper error code for invalid date
}
let order = Calendar.current.compare(Date() , to: validDateFound, toGranularity: .day)
switch order {
case .orderedAscending:
return(2)
case .orderedDescending:
return(1)
case .orderedSame:
return(0)
}
}
The only case where you won't get a proper date is if the date
is empty or it doesn't match the date format you have mentioned.
Also don't force unwrap. Safely unwrap and handle the error case for invalid date input.
You can check this link for more information on date formats.