How do I make a text label in a table view cell show "dd-MM-yyyy " instead of ISO 8601 retrieved from a web service ?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
cell.authorName.text = articles?[indexPath.row].author
cell.headLine.text = articles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill"))
cell.timePublication.text = articles?[indexPath.row].publishedAt
return cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
cell.authorName.text = articles?[indexPath.row].author
cell.headLine.text = articles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill"))
cell.timePublication.text = articles?[indexPath.row].publishedAt
return cell
}
If you want to work with a certain date format specified in ISO8601, you should better consider using ISO8601DateFormatter.
And creating a DateFormatter is relatively a heavy work in iOS, so you should create an instance outside the method once, and reuse it repeatedly in the method.
The code would be something like this:
One more, you should better consider adopting Decodable. Some specific date formats like ISO8601 can be converted into Date while decoding JSON.
And creating a DateFormatter is relatively a heavy work in iOS, so you should create an instance outside the method once, and reuse it repeatedly in the method.
The code would be something like this:
Code Block ///To convert API result date (ISO8601) to `Date`, this property should not be inside any methods let inDateFormatter = ISO8601DateFormatter() ///To convert `Date` to readable date format, this property should not be inside any methods let outDateFormatter: DateFormatter = { let df = DateFormatter() df.dateFormat = "dd-MM-yyyy" df.locale = Locale(identifier: "en_US_POSIX") return df }() func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell cell.authorName.text = articles?[indexPath.row].author cell.headLine.text = articles?[indexPath.row].title cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill")) if let dateString = articles?[indexPath.row].publishedAt, let date = inDateFormatter.date(from: dateString) { let formattedString = outDateFormatter.string(from: date) cell.timePublication.text = formattedString } else { cell.timePublication.text = "----------" } return cell }
One more, you should better consider adopting Decodable. Some specific date formats like ISO8601 can be converted into Date while decoding JSON.