Search code examples
iosswiftdatensdateformatterutc

DateTime2 formart conversion to Swift Date


I have a date string coming from back-end as "2022-08-16T13:44:11.8743234". Date formatting and conversion is the oldest skill in the book but I cannot figure out why I'm unable to convert that string to a Date object in Swift iOS. I just get nil with any source format I specify.

private func StringToDate(dateString: String) -> Date?
{
    let formatter = DateFormatter()
    formatter.dateFormat = "YYYY-MM-DDTHH:mm:ss.[nnnnnnn]"
    let date = formatter.date(from: dateString)
    return date //this is nil every time
}

DateTime2 is a more precise SQL Server extension of the normal C# DateTime, hence why the date string has 7 decimal places afters the seconds.

What am I doing wrong?


Solution

  • In your code the way you are handling the millisecond part is wrong. We use usually .SSS for milliseconds. Take a look at here it shows all the symbols related to date format.

    let dateFormatter = DateFormatter()
    dateFormatter.locale     = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
    let date = dateFormatter.date(from: "2022-08-16T13:44:11.8743234")
    print(date)
    

    In addition to that you are using DD for day. DD means the day of the year(numeric). So it should be dd. Same case is applied for the year as well.