Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
315 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...