1

I am trying to figure out how to change the output of the below code.

It returns: Optional(2017-11-09 04:54:51 + 00000

I only want the date value 2017-11-09

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let ots = otsProcessConfirmations[indexPath.row]

    cell.textLabel?.text = ots.otsBranch
    cell.detailTextLabel?.text = String(describing: otsProcessConfirmations[indexPath.row].otsDate)

    return cell
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

2

You need to use a DateFormatter. All though a default style may suit your needs, you can also put in custom formats using tr35-31 date format patterns.

First create a date formatter property so you don't continously remake one everytime you dequeue a cell.

lazy var dateFormatter: DateFormatter {
    let df = DateFormatter()

    df.dateFormat = "yyyy-MM-dd"
    // You could also try this, it will output something like: 2017/11/09
    // df.dateStyle = DateFormatter.Style.short

    return df
}()

Then in your tableView(_:cellForRowAt:) Method

// replace the cell.detailTextlabel... line with this
if let date = ots.otsDate {
    cell.detailTextLabel?.text = dateFormatter.string(from: date)
}

Wrote all the code out of my head, so my apologies if there are any errors.

ColdLogic
  • 7,206
  • 1
  • 28
  • 46
  • The use of `dateStyle` is better than using `dateFormat` since the result is appropriate for the user's locale. – rmaddy Nov 10 '17 at 00:00
  • @rmaddy True for simple cases. However, designers usually want a specific format, which most of the time has nothing to do with a users locale, unfortunately. From the `DateFormatter.Style` documentation: `Do not use these constants if you want an exact format.` But if the default styles work, by all means, use them for the locale benefits. – ColdLogic Nov 10 '17 at 00:04
  • by looking at OP code the property you should access is otsDate not date. `if let date = ots.otsDate {`. Btw I agree with @rmaddy. You shouldn't choose how the user will format a date. You should use dateStyle. The only thing you should determine is if it will be displayed short, medium, long or full. https://stackoverflow.com/a/28347285/2303865 – Leo Dabus Nov 10 '17 at 02:06
1

You can use extension of Date

extension Date{
    var dateString: String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter.string(from: self)
    }
}

In your class

let ots = otsProcessConfirmations[indexPath.row]

if let date = ots.otsDate {
    cell.detailTextLabel?.text = date.dateString
}
BIJU C
  • 21
  • 5