Search code examples
swiftdatensdatensdateformatter

Why would my DateFormatter .date(from: String) return nil


Been using this function to covert a String to a Date Object.
Similar Qs on SO, however could not find one that handles my case of just the time. So this post I believe is not a duplicate.

    func convertTimeStringToDate() -> Date {
                //time will be "04:48"
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "HH:mm"
                dateFormatter.dateStyle = .none
                dateFormatter.timeStyle = .short
                dateFormatter.locale = Locale.current
                return dateFormatter.date(from: "04:48")!
            }

The function returns nil so crashes as its unwrapped!. I can not see what's wrong with the code.


Solution

  • This is how your method should be. dateStyle and timeStyle change the format again.

    func convertTimeStringToDate() -> Date {
        //time will be "04:48"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        dateFormatter.locale = Locale.current
        return dateFormatter.date(from: "04:48")!
    }
    

    However, it's interesting to note that the last date format is considered valid. So, if you set the formats in reverse order, it will work!

    P.S - I've only seen dateStyle and timeStyle used for output formatting.


    Note: If there is a chance that you input format might change then you should safely unwrap your date and have a default date in place or something so that it doesn't crash your app.