Home > Software design >  Getting difference between two dates like in facebook, instagram comment section
Getting difference between two dates like in facebook, instagram comment section

Time:12-06

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"

CodePudding user response:

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 dateStr in an unexpected format dateFormatter.date(from: dateStr!) will return nil. So the value of the exampleDate will be equal to Date().

So in your calculation you are comparing Date() and Date(). Which are same. So there is no difference and it will return "in 0 seconds".

So print your dateStr (before passing it to the dateformatter) and check if it is in correct formate. It might have some extra space or any other thing included.

  • Related