Search code examples
arraysswiftnsdateformatter

Convert date String to dateformatter in an array


I fetch data from an API. In this API, there is an date element that comes in String Here is the format of getting this date info:

 cell.nameLabel.text = timelineData[indexPath.row].updatedAt

and here is the string date format: "2013-01-03T17:24:28Z"

I want to sort this array base of the this date, but I think I should first convert it to the date format from String, is it right?

If yes, could you help me to how to do that? Can I do it in the same array or I have to create a new array for that? I will be appreciated if you can help me on that. Thanks


Solution

  • The ISO8601 date string format is sortable. You can sort the array descending in place

    timelineData.sort{$0.updatedAt > $1.updatedAt}
    

    The newest item comes first. If you want the oldest item first replace > with <