Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 将ISO8601字符串转换为重新格式化的日期字符串(Swift)_Ios_Swift_Iso8601_Dateformatter - Fatal编程技术网

Ios 将ISO8601字符串转换为重新格式化的日期字符串(Swift)

Ios 将ISO8601字符串转换为重新格式化的日期字符串(Swift),ios,swift,iso8601,dateformatter,Ios,Swift,Iso8601,Dateformatter,我正在从JSON数据库中提取日期。日期的格式为2017-06-16T13:38:34.601767(我想是ISO8601)。我正在尝试使用ISO8601DateFormatter格式化2017-06-16T13:38:34.601767到2017-06-16的日期。到目前为止,我甚至无法将提取的字符串格式化为日期 let pulledDate = self.pulledRequest.date var dateFormatter = ISO8601DateFormatter() let date

我正在从JSON数据库中提取日期。日期的格式为2017-06-16T13:38:34.601767(我想是ISO8601)。我正在尝试使用ISO8601DateFormatter格式化2017-06-16T13:38:34.601767到2017-06-16的日期。到目前为止,我甚至无法将提取的字符串格式化为日期

let pulledDate = self.pulledRequest.date
var dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: pulledDate)
print(date!) //nil
我不确定我的日期格式是否错误,它不是ISO8601,或者我是否没有按预期使用ISO8601数据格式

1.)这是ISO8601日期吗?
2.)我是否正确使用ISO8601数据格式化程序


谢谢

ISO8601有几个不同的选项,包括时区。默认情况下,
ISO8601DateFormatter
希望字符串中包含时区指示器。您可以使用如下自定义选项禁用此行为:

let pulledDate = "2017-06-16T13:38:34.601767"
var dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime, .withDashSeparatorInDate, .withColonSeparatorInTime]
let date = dateFormatter.date(from: pulledDate)
如果您想知道默认选项是什么,只需在游乐场中运行以下代码:

let dateFormatter = ISO8601DateFormatter()
let options = dateFormatter.formatOptions
options.contains(.withYear)
options.contains(.withMonth)
options.contains(.withWeekOfYear)
options.contains(.withDay)
options.contains(.withTime)
options.contains(.withTimeZone)
options.contains(.withSpaceBetweenDateAndTime)
options.contains(.withDashSeparatorInDate)
options.contains(.withColonSeparatorInTime)
options.contains(.withColonSeparatorInTimeZone)
options.contains(.withFullDate)
options.contains(.withFullTime)
options.contains(.withInternetDateTime)
当然,如果字符串不包含时区,则日期格式化程序仍将使用其
timezone
属性在时区中对其进行解释,根据文档,该属性默认为GMT

如果要在不同的时区中解释日期,请记住在使用格式化程序之前对其进行更改:

dateFormatter.timeZone = TimeZone(identifier: "Europe/Paris")

您确定毫秒块(.601767)中有6位数字吗?很遗憾,是的。这也让我很沮丧。我在某处看到其他人(我知道,这很有帮助lol)说他们有相同的东西,它是ISO8601输出是2017-06-16 13:38:34+0000-有没有办法使用格式化程序截断+0000?使用另一个具有相同选项的格式化程序,再加上
with spacebetween和time
选项。