0
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2018-07-18T17:02:02.614Z")

日期描述打印:2015-06-18 17:02:02 +0000 Playground 似乎自然地在右侧输出:“2015 年 6 月 18 日上午 10:02”

如何格式化它以显示这个?“2018 年 7 月 18 日上午 10:02”

谢谢!

4

1 回答 1

1

您需要date使用Date另一个DateFormatter. 您应该使用日期和时间样式,而不是固定格式。

而且“UTC”不是语言环境,而是时区。但你不需要那个。但是您应该en_US_POSIX在解析固定格式的日期字符串时使用特殊的语言环境。

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2018-07-18T17:02:02.614Z")
if let date = date {
    let outputFormatter = DateFormatter()
    outputFormatter.dateStyle = .medium
    outputFormatter.timeStyle = .short
    let output = outputFormatter.string(from: date)
    print(output)
}

输出:

2018 年 7 月 18 日上午 11:02

请注意,时间将取决于您当地的时区。默认情况下,输出将是本地时间,所以不要期望输出是17:02因为那是 UTC 时区的时间。

于 2018-07-30T22:38:08.737 回答