【问题标题】:Why would my DateFormatter .date(from: String) return nil为什么我的 DateFormatter .date(from: String) 返回 nil
【发布时间】:2019-03-10 15:41:49
【问题描述】:

一直在使用此函数将字符串转换为日期对象。
SO上的类似Qs,但是找不到一个能处理我当时情况的问题。所以我相信这篇文章不是重复的。

    func convertTimeStringToDate() -> Date {
                //time will be "04:48"
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "HH:mm"
                dateFormatter.dateStyle = .none
                dateFormatter.timeStyle = .short
                dateFormatter.locale = Locale.current
                return dateFormatter.date(from: "04:48")!
            }

该函数返回 nil,因此在展开时崩溃!。我看不出代码有什么问题。

【问题讨论】:

  • 这样一个函数的目的是什么?您可以通过 DateComponents 以更可靠的方式创建有效日期。
  • 您已经将 dateFormat 指定为“HH:mm”,这对您的输入有效。那你为什么还要指定dateStyletimeStyle 来改变格式呢?这就是它崩溃的原因。
  • 就是这样。我已经使用该功能几个月了。我想最新的 beta 版本阻止了我摆脱它。请把它作为答案,我会接受

标签: swift date nsdate nsdateformatter


【解决方案1】:

这就是你的方法应该的样子。 dateStyletimeStyle 再次更改格式。

func convertTimeStringToDate() -> Date {
    //time will be "04:48"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"
    dateFormatter.locale = Locale.current
    return dateFormatter.date(from: "04:48")!
}

不过,有趣的是,最后一个日期格式被认为是有效的。因此,如果您以相反的顺序设置格式,它将起作用!

P.S - 我只看到 dateStyletimeStyle 用于输出格式。


注意:如果您输入的格式可能会更改,那么您应该安全地打开日期并设置默认日期或其他东西,以免您的应用程序崩溃。

【讨论】:

    【解决方案2】:

    请不要设置 dateStyle 和 timeStyle。

    func convertTimeStringToDate() -> Date {
        //time will be "04:48"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        dateFormatter.locale = Locale.current
        return dateFormatter.date(from: "04:48")!
    }
    

    【讨论】:

    • 欢迎来到 Stackoverflow 并感谢您的贡献。但是问题已经得到解答,并且您的观点已经提出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    相关资源
    最近更新 更多