swift 3 - can not convert string to date [duplicate]

心不动则不痛 提交于 2019-12-25 18:45:13

问题


No matter what I do, I can not convert an RSSs pubDate (which is a string of course) into a Date.

Here is the date String: Sun, 02 Apr 2017 19:31:18 GMT

Here is my code:

private var dateBuffer: Date {
    formatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss zzz"
    let date = formatter.date(from: buffers["pubDate"]!) //<-date comes back nil
    return date! //<-program crashes
}

date always returns nil. What maybe the problem??


回答1:


If your are pretty sure that buffers["pubDate"]! is equal to "Sun, 02 Apr 2017 19:31:18 GMT" (or any date with the same format), then it should be:

var dateBuffer: Date {
    let formatter = DateFormatter()
    formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
    let date = formatter.date(from: buffers["pubDate"]!)
    return date!
}

Note that the difference is HH:mm:ss instead of hh:mm:ss. For reading the hours as 24-clock convention, you should use HH.

Also, to be more safe -from any unexpected crash-, I'd suggest to do some optional binding, as follows:

var dateBuffer: Date? {
    let formatter = DateFormatter()
    let str:String? = "Sun, 02 Apr 2017 19:31:18 GMT"

    formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
    if let pubDate = buffers["pubDate"], let date = formatter.date(from: pubDate) {
        return date
    }

    return nil
}

if let myDate = dateBuffer {
    print(myDate)
}



回答2:


It looks like you are using another language / locale than English but the name of your Weekday is in English ("Sun").

The formatter will work as expected, if you set the locale to English:

formatter.locale = Locale(identifier: "en")

Also, the format must be EEE, dd MMM yyyy HH:mm:ss zzz (with capital H because of 24 hour time)



来源:https://stackoverflow.com/questions/43298652/swift-3-can-not-convert-string-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!