日期格式化程序 - 仅显示日期

时间:2017-11-09 23:36:55

标签: ios swift

我试图弄清楚如何更改以下代码的输出。

返回:可选(2017-11-09 04:54:51 + 00000

我只想要日期值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
}

2 个答案:

答案 0 :(得分:2)

您需要使用DateFormatter。虽然默认样式可能符合您的需求,但您也可以使用tr35-31 date format patterns

添加自定义格式

首先创建一个日期格式化程序属性,这样每次出列单元格时都不会连续重新格式化。

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
}()

然后在您的tableView(_:cellForRowAt:)方法

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

写下了我的所有代码,所以如果有任何错误我会道歉。

答案 1 :(得分:1)

您可以使用extension中的Date

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

在您的课堂上

let ots = otsProcessConfirmations[indexPath.row]

if let date = ots.otsDate {
    cell.detailTextLabel?.text = date.dateString
}
相关问题