[英]iOS: dateformatter in swift return nil
I have this code in my app 我的应用程式中有这个程式码
service.requestLastDate{ (response) -> () in
var str = response as NSString
var d = str.stringByReplacingOccurrencesOfString("\"", withString: "")
println("D \(str)") // D 2015-05-25 08:13:33
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
var date_formatted = dateFormatter.dateFromString(d)
println("DATE FORMATTED \(date_formatted)") // is NIL
with this code date_formatted is ever nil. 使用此代码date_formatted永远为零。 If I print in consolle "d" the result is "2015-02-12 08:15:16", this string is a real string.
如果我在控制台“ d”中打印,结果为“ 2015-02-12 08:15:16”,则此字符串为真实字符串。 If I try to use the string "example" I get a correct date_formatted.
如果我尝试使用字符串“ example”,则会得到正确的date_formatted。 What happen?
发生什么事? I can't understand.
我听不懂 I just tried changing NSLocale and the timezone for the dateFormatter but I have ever the same result.
我只是尝试为dateFormatter更改NSLocale和时区,但结果却相同。
this is the request 这是要求
func requestLastDate(completion:(response:NSString)->()){
my_req_date = request(.GET, "http://example.com/current_date")
.responseString { (_, _, string, error) in
println(" server \(string!)") //server "2015-05-25 08:13:33"
completion(response: string!)
}
}
Hate to break it :) 讨厌打破它:)
Think it might be: 认为可能是:
"yyyy-MM-dd HH:mm:ss"
not 不
"yyyy-MM-dd HH:mm"
? ?
Check your respsonse for that it translates to a proper date-formatted string. 检查您的响应,以确保它可以转换为正确的日期格式的字符串。 Because if I try this, it works:
因为如果我尝试这样做,它将起作用:
var response:AnyObject?
response = "2015-03-17 23:34:12"
if let date:AnyObject = response {
var d = date as! String
var example = "2015-03-17 23:34:12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var date_formatted = dateFormatter.dateFromString(d)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.