Search code examples
swiftdateformatter

DateFormatter returns nil


Why does DateFormatter return nil? I think the string format matches?

let dateString = ("01/05/2017")!
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "dd/MMM/yyyy"
let dateObj = dateFormatter.date(from: dateString)

After executing the code above, the dateObj is nil.


Solution

  • For month you need to use MM because MMM is used when you having month in the format like Jan,Feb,Mar and so on. So your dateFormat should be dd/MM/yyyy.

    let dateString = "01/05/2017"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    let dateObj = dateFormatter.date(from: dateString)
    

    Note: No need to set timeZone to TimeZone.current