DateFormatter returns nil

强颜欢笑 提交于 2019-12-13 11:24:12

问题


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.


回答1:


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




回答2:


Replace with your dateFormat:

dateFormatter.dateFormat = "dd/MM/yyyy"



回答3:


date Formatter should be dateFormatter.dateFormat = "dd/MM/yyyy" in this case.




回答4:


You can check various date format from given link

NSDateFormatter

For given example you can use let formaterStrig = "dd/MM/yyyy"



来源:https://stackoverflow.com/questions/44328577/dateformatter-returns-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!