Swift2:字符串到日期,格式化并返回字符串。没有发现
Swift2: String to date, format it and back to string. Found nil
我有一个日期字符串:Sun, 07 Feb 2016 21:16:21 +0000
并且需要它:dd.MM.yyyy
以下方法抛出 fatal error: nil
if parsedElement == "date" {
if currentArticle.date.isEmpty {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
let tempDate = dateFormatter.dateFromString(str)
dateFormatter.dateFormat = "dd.MM.yyyy"
let convertedDate = dateFormatter.stringFromDate(tempDate!)
currentArticle.date = convertedDate
}
}
调试:
str String "Sun, 07 Feb 2016 21:16:21 +0000"
tempDate NSDate? 2016-02-07 21:16:21 UTC 0xe41bc67eba500000
convertedDate String "07.02.2016"
看起来不错,但是当我释放“currentArticle.date = convertedDate
”时,它说 convertedDate = nil
想法?
PS: currentArticle.date == isEmpty
编辑: if 循环运行了 5 次。
如果我给出 currentArticle.date = str
(仅日期字符串),这就是调试器所说的:
1. str String "Sun, 07 Feb 2016 21:16:21 +0000"
2. str ""
3. str String "Thu, 04 Feb 2016 21:18:34 +0000"
4. str ""
5. str String "Thu, 04 Feb 2016 18:57:14 +0000"
您收到致命错误:
unexpectedly found nil while unwrapping an Optional value -> tempDate
我假设您在以下行中遇到此错误:
let convertedDate = dateFormatter.stringFromDate(tempDate!)
这是因为你强制展开一个等于 nil 的可选值。您应该使用可选绑定来解包它,即:
if let tempDate = tempDate {
let convertedDate = dateFormatter.stringFromDate(tempDate)
currentArticle.date = convertedDate
}
现在,为什么您的日期格式化程序在这种情况下不返回 str
的值的问题完全与您的数据有关。您可以在上面的可选绑定代码块中添加一个 else
以在本例中显示 str
以缩小问题范围。
我有一个日期字符串:Sun, 07 Feb 2016 21:16:21 +0000
并且需要它:dd.MM.yyyy
以下方法抛出 fatal error: nil
if parsedElement == "date" {
if currentArticle.date.isEmpty {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
let tempDate = dateFormatter.dateFromString(str)
dateFormatter.dateFormat = "dd.MM.yyyy"
let convertedDate = dateFormatter.stringFromDate(tempDate!)
currentArticle.date = convertedDate
}
}
调试:
str String "Sun, 07 Feb 2016 21:16:21 +0000"
tempDate NSDate? 2016-02-07 21:16:21 UTC 0xe41bc67eba500000
convertedDate String "07.02.2016"
看起来不错,但是当我释放“currentArticle.date = convertedDate
”时,它说 convertedDate = nil
想法?
PS: currentArticle.date == isEmpty
编辑: if 循环运行了 5 次。
如果我给出 currentArticle.date = str
(仅日期字符串),这就是调试器所说的:
1. str String "Sun, 07 Feb 2016 21:16:21 +0000"
2. str ""
3. str String "Thu, 04 Feb 2016 21:18:34 +0000"
4. str ""
5. str String "Thu, 04 Feb 2016 18:57:14 +0000"
您收到致命错误:
unexpectedly found nil while unwrapping an Optional value -> tempDate
我假设您在以下行中遇到此错误:
let convertedDate = dateFormatter.stringFromDate(tempDate!)
这是因为你强制展开一个等于 nil 的可选值。您应该使用可选绑定来解包它,即:
if let tempDate = tempDate {
let convertedDate = dateFormatter.stringFromDate(tempDate)
currentArticle.date = convertedDate
}
现在,为什么您的日期格式化程序在这种情况下不返回 str
的值的问题完全与您的数据有关。您可以在上面的可选绑定代码块中添加一个 else
以在本例中显示 str
以缩小问题范围。