Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading