简体   繁体   English

NSDateFormatter.dateFromString返回nil(“ yyyy-MM-dd”到NSDate)

[英]NSDateFormatter.dateFromString returns nil (“yyyy-MM-dd” to NSDate)

Having a problem with NSDateFormatter. NSDateFormatter有问题。

So I have a date string formatted "yyyy-MM-dd" , for example 2015-09-22. 所以我有一个日期字符串,格式为"yyyy-MM-dd" ,例如2015-09-22。 However when I pass this into NSDateFormatter.dateFromString, the method returns nil. 但是,当我将其传递给NSDateFormatter.dateFromString时,该方法返回nil。 My code is as follows: 我的代码如下:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let dateAsNSDate = dateFormatter.dateFromString(payload.objectForKey("messageExpiry") as! String)

From the debugger console at a breakpoint just above this code: 从调试器控制台中位于此代码上方的断点处:

po payload.objectForKey("messageExpiry") as! String

"2015-09-31"

I have explored other questions similar to this but am as of yet still unable to fix this problem. 我已经探索了与此类似的其他问题,但到目前为止仍无法解决此问题。 Any and all help would be appreciated. 任何和所有帮助将不胜感激。

Your code is correct and produces the expected result eg for the input string "2015-09-22". 您的代码是正确的,并且会产生预期的结果,例如输入字符串“ 2015-09-22”。 For the input "2015-09-31" however, nil is returned because that is an invalid date: September has only 30 days. 但是,对于输入“ 2015-09-31”,将返回nil ,因为这是一个无效日期:9月只有30天。

You can set 你可以设定

dateFormatter.lenient = true

and then "2015-09-31" is accepted and treated as "2015-10-01". 然后接受“ 2015-09-31”并将其视为“ 2015-10-01”。 But you should check first why payload.objectForKey("messageExpiry") returns an invalid date. 但是,您应该先检查一下payload.objectForKey("messageExpiry") 为什么返回无效日期。

var str = "2015-09-29"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let dateAsNSDate = dateFormatter.dateFromString(str)
print(dateAsNSDate)
// -> "Optional(2015-09-29 07:00:00 +0000)\n"

So that would appear to work. 这样看来可行。 Looks like you just got too many days in your month, so it wasn't a valid date! 看来您一个月中的日子太多了,所以这不是一个有效的日期! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM