skip to Main Content

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

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search