1

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"

Abhinandan Pratap
  • 2,142
  • 1
  • 18
  • 39
  • 1
    I got it. What happens is ```dateFormatter.date(from: dateStr!)``` returns ```nil```. So the value of the ```exampleDate``` equals to ```Date()```. So in your calculation you are comparing ```Date()``` and ```Date()```. which is exactly ```0 seconds```. So print your ```dateStr```(before passing it to dateformatter) and check if it is in correct formate. It might have some extra space or any other thing included – udi Dec 05 '22 at 07:20
  • 1
    @udi thanks for help i checked and remove the additional spaces ocurred in label. now it is working fine – Abhinandan Pratap Dec 05 '22 at 07:27

1 Answers1

1

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.

udi
  • 3,672
  • 2
  • 12
  • 33