Search code examples
swiftdatetimezonensdatensdateformatter

Converting string to date returns nil


I am trying to convert my string to a date using a static date formatter. When I make the call to stringToDate() using the variables below, a nil value is returned.

I've checked previous posts about this issue where people are saying it's because of the dateformatter locale or timeZone. However, that doesn't seem to be the issue in this case.

Does anyone know what the issue could be in this case? My code is below:

import Foundation

class DateHelper {

    private static let dateFormatter: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd hh:mm:ss"
        df.locale = Locale(identifier: "en_GB")
        df.timeZone = TimeZone.current
        return df
    }()

    static func stringToDate(str: String, with dateFormat: String) -> Date? {
        dateFormatter.dateFormat = dateFormat
        let date = dateFormatter.date(from: str)

        return date
    }
}

var myDate = Date()
var dateStr = "2019-02-19T17:10:08+0000"

print(DateHelper.stringToDate(str: dateStr, with: "MMM d yyyy")) // prints nil

Solution

  • Looks like your string is in ISO8601 format. Use the ISO8601DateFormatter to get date instance. You can use ISO8601DateFormatter.Options to parse varieties of ISO8601 formats. For your string,

    For Swift 4.2.1

    let formatter = ISO8601DateFormatter()
    let date = formatter.date(from: dateStr)
    print(date!)
    

    Should output

    "2019-02-19 17:10:08 +0000\n"