如何将 DateTime 转换为字符串

How convert DateTime to string

我从 DateTime 的服务器响应中得到这样的信息:

2019-04-24T16:25:02.557Z

我只想在字符串中:

2019-04-23

我该怎么做?

我的代码:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let d = job.postedAt
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)
    destinationVC.createdJob = k
} else {
    print("There was an error decoding the string")
}

试试,

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd"
let d = "2019-04-24T16:25:02.557Z"
if let date = dateFormatter.date(from: d) {
    let k = dateFormatterPrint.string(from: date)

    print(k)
} else {
    print("There was an error decoding the string")
}

您的 dateFormatter.dateFormat 应该是 yyyy-MM-dd'T'HH:mm:ss.SSS'Z',您的 dateFormatterPrint.dateFormat 应该是 yyyy-MM-dd

要将 2019-04-24T16:25:02.557Z 转换为 Date 对象,您需要使用:

let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions.insert(.withFractionalSeconds)
guard let date = iso8601DateFormatter.date(from: "2019-04-24T16:25:02.557Z") else { return }

然后在 UI 中只输出一个日期字符串,没有时间,你可以使用类似的东西:

let outputFormatter = DateFormatter()
outputFormatter.dateStyle = .medium
let result = outputFormatter.string(from: date)

这个呢?

func stringFromDate(_ date: Date) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
    return formatter.string(from: date)
}