问题
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