Swift: Converting string to date

1.3k Views Asked by At

I have a date as String but I want to convert it to Date.

The date in string looks like this - "2022-09-09T07:00:00.0000000".

Code to convert it to Date:

public static func dateStringToDate(dateString: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale.autoupdatingCurrent
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.setLocalizedDateFormatFromTemplate("MM-dd-yyyy HH:mm:ss")
    return dateFormatter.date(from: dateString)
}

No matter what I do, I keep getting nil as the output. I tried with ISO8601 template as well and got nil. I commented out line "setLocalizedDateFormatFromTemplate" but still got nil. Can't figure out what am I missing or doing wrong in the code.

2

There are 2 best solutions below

0
Rob C On

First of all, this is an excellent resource. I think what you are looking for is this:

func dateStringToDate(dateString: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS"
    return dateFormatter.date(from: dateString)
}

dateStringToDate(dateString: "2022-09-09T07:00:00.0000000")

Sep 9, 2022 at 7:00 AM

You have the year, then month, then day, then hour, minute, second, fractional seconds

0
Ashwani Kumar On

Use this Snippet of code

func dateStringToDate(dateString: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale.autoupdatingCurrent
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
    return dateFormatter.date(from: dateString)
}

You were not providing the proper date format