I am working on an app in which i have to display the date/time difference between current date and posted date in format like "1 hour ago", "4 days ago" I got api response in this format
"created_at": "2022-12-03 05:24:00"
and i am using this code to convert this date string to relative date
let dateStr = cell.dateLbl.text //
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print("==", dateFormatter.date(from: dateStr!) ?? Date())
let exampleDate = dateFormatter.date(from: dateStr!) ?? Date()
print(exampleDate)
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
let relativeDate = formatter.localizedString(for: exampleDate, relativeTo: Date())
print(relativeDate)
cell.dateLbl.text = relativeDate
it always return
"in 0 seconds"
I executed the code in the playground and it works fine. So there is nothing much wrong with the logic.
But this is what might happen. If the
dateStrin an unexpected formatdateFormatter.date(from: dateStr!)will returnnil. So the value of theexampleDatewill be equal toDate().So in your calculation you are comparing
Date()andDate(). Which are same. So there is no difference and it will return"in 0 seconds".So print your
dateStr(before passing it to thedateformatter) and check if it is in correct formate. It might have some extra space or any other thing included.