如何在dateFormatter中添加字符

Hon*_*ney -2 date swift

我按照这个答案,但它对我不起作用.

我想把我的时间格式化为:

"2017-09-11 T 11:45:00-04:00"

我正在做:

let xFormatter = DateFormatter()
xFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ss-04:00"
print(xFormatter.string(from: date))
Run Code Online (Sandbox Code Playgroud)

我需要一个日期和时间之间的T. 但是,如果我添加它,我的格式变成如下:

2017年9月11日

(最后-4:00是我硬编码的时间偏移...)

vad*_*ian 7

添加单引号

xFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-04:00"
Run Code Online (Sandbox Code Playgroud)

从文档:

...这包括如果要将ASCII字母用于表示文字文本,则需要将ASCII字母括在单引号中.

来源:Unicode.org:日期格式模式

编辑:

请注意,时区只是对字符串的修改,日期格式化程序不会考虑它.

要考虑时区,您必须设置timeZone格式化程序

xFormatter.timeZone = TimeZone(secondsFromGMT: -14400)
Run Code Online (Sandbox Code Playgroud)

在iOS 10.0+和macOS 10.12+中,有一种更方便的方法来创建ISO8601字符串

let isoFormatter = ISO8601DateFormatter()
isoFormatter.timeZone = TimeZone(secondsFromGMT: -14400)
isoFormatter.formatOptions = .withInternetDateTime
print(isoFormatter.string(from: Date()))
Run Code Online (Sandbox Code Playgroud)