-2

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.

tech_human
  • 6,592
  • 16
  • 65
  • 107

2 Answers2

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

Rob C
  • 4,877
  • 1
  • 11
  • 24
1

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

Ashwani Kumar
  • 465
  • 4
  • 9