Search code examples
iosswiftnsdateformatter

Converting time from String to Date crashes on Simulator only


Currently I am using this code to convert a time from String to Date:

public static func dateFromTime(_ time: String) -> Date {
    let formatter = DateFormatter()
    formatter.dateFormat = "k:mm"
    formatter.locale = NSLocale.current

    return formatter.date(from: time)!
}

This works on my device, but it crashes on the simulator. Both of them uses the 12 hour format from what I can see.

The string that this method receives when it crashes is "5:30 AM".

Any other reason why this code may crash on simulator and not device ?


Solution

  • Your code crashed because of proper date format !

    For , "5:30 AM" use "h:mm a" , instead of "k:mm" .

    To avoid any kind of crashes , update your code like below . .

    public static func dateFromTime(_ time: String) -> Date {
            let formatter = DateFormatter()
            formatter.dateFormat = "h:mm a"
            formatter.locale = NSLocale.current
            if let date = formatter.date(from: time)
            {
                return date
            }
            print("Invalid arguments ! Returning Current Date . ")
            return Date()
        }