简体   繁体   中英

what am I missing in my dateFormatter function?

I'm trying to create a function to convert a String to Date in swift from an API. I've seen a lot of examples about that and tried to do the same but it always returns nil.

let dateStr = "1996-11-24T09:02:32Z"

func toDate(str: String) -> Date? {
    let dateForm = DateFormatter()
    dateForm.dateFormat = "dd-MM-yyyy"
    dateForm.locale = Locale(identifier: "en_US")
    let date = dateForm.date(from: str)
    return date
}


print(toDate(str: dateStr)) // always prints nil

I've tried to tweak, change location, remove location, change dateFormat but nothing works.

what might be wrong here?

thank you in advance

Since your date is 1996-11-24T09:02:32Z and you are using formate dd-MM-yyyy which does not match. so you need to replace dd-MM-yyyy with yyyy-MM-dd'T'HH:mm:ssZ and it will work fine.

And your result will be:

let dateStr = "1996-11-24T09:02:32Z"

func toDate(str: String) -> Date? {
    let dateForm = DateFormatter()
    dateForm.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    dateForm.locale = Locale(identifier: "en_US_POSIX")
    let date = dateForm.date(from: str)
    return date
}


print(toDate(str: dateStr)) // "Optional(1996-11-24 09:02:32 +0000)\n"

Or you can use short way as dan suggested:

func toDate(str: String) -> Date? {
    return ISO8601DateFormatter().date(from: str)
}

print(toDate(str: dateStr)) // "Optional(1996-11-24 09:02:32 +0000)\n"

Or if you prefer an Extension

extension Formatter {
    static let iso8601 = ISO8601DateFormatter()
}

let dateStr = "1996-11-24T09:02:32Z"
Formatter.iso8601.date(from: dateStr) // "Nov 24, 1996 at 2:32 PM"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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