当输入的日期是 swift 中月份的最后一天时,NSDateFormatter 导致崩溃

NSDateFormatter causing crash when the date entered is the last day of the month in swift

我遇到了一个从字符串中获取 NSDate 的奇怪问题,如果输入的日期是该月的最后一天(例如:2016-3-31),应用程序会崩溃并显示 "unexpectedly found nil while unwrapping an Optional value." Here是我用来实现这个的 NSDate 扩展:

extension NSDate {
convenience
init(dateString:String) {
    let dateStringFormatter = NSDateFormatter()
    dateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")


            let d = dateStringFormatter.dateFromString(dateString)!
            self.init(timeInterval:0, sinceDate:d)
    }
}

它在以下行崩溃:

let d = dateStringFormatter.dateFromString(dateString)!

我认为这意味着它无法将字符串变成 NSDate。但是,只有当日期是该月的最后一天时才会发生。如果我更改输入的字符串,例如,从“2016-3-31 02:00:00”更改为“2016-3-30 02:00:00”,它运行得很好。如果有人能帮我解决这个问题,将不胜感激。

编辑:这段代码工作正常。问题最终出现在我用来计算输入字符串的代码中,该代码将一天加 1。我还将其更改为 "if let" 语句,以避免将来因类似疏忽而导致崩溃。由于它可能对其他人有用,这里是我使用的代码:

    if let d = dateStringFormatter.dateFromString(dateString)  {
    self.init(timeInterval:0, sinceDate:d)
    } else {
        let d = dateStringFormatter.dateFromString("2017-12-15 00:00:00")
        self.init(timeInterval:0, sinceDate:d!)
    }

嗯 - 运行 你的代码在 Playground 中提供的字符串完美运行。

您可能要检查的一件事是您的字符串格式在其他地方没有被窃听,因为这段代码看起来不错,并且错误表明它无法生成 d.