Search code examples
iosswiftnsdateformatterdateformatter

Date formatter not returning date from string in app works in playground though


I know these questions are asked all the time about date formatters, however the issue I have is really odd

I need to convert a simple string to date as follows

    let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let dateOfBirthString = "10/20/2002"
let dob: Date? = dateFormatter.date(from: dateOfBirthString)

This works fine in a playground but always returns nil in the app (with those exact values (albeit properties rather than hard coded strings)

Any help would be appreciated, its driving me nuts


Solution

  • extension String {
    
    func toDateTime() -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = TimeZone(identifier: "UTC")
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        guard let date = dateFormatter.date(from: self) else {
            preconditionFailure("Take a look to your format")
        }
        return date
    }
    }
    

    try this extension

    let dateOfBirthString = "10/20/2002"
    let dob: Date? = dateOfBirthString.toDateTime()
    

    use this extension like this and if you get any error then feel free to comment below