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

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

ios - I get nil when using NSDateFormatter in swift

This is my code :

println(myStringDate)    // 2015-02-26T17:46:34.000Z
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDTHH:mm:ss.sssZ"
let myDate = dateFormatter.dateFromString(myStringDate)
println(myDate)        // nil

Why nil ? What am I doing wrong ?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Your problem is how you set the date format. Because there is a T in your string, you need to "escape" it and say, that it shouldn't affect the formatting of the date.

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Also as you see, I've changed the sss to SSS which stands for miliseconds and also changed the year YYYY to lowercase yyyy also the same with the DD. You have to be really carefully, when to use upper and lowercase letters in your Dateformat-strings.

Check @HotLicks link in the comments which shows a great overview of the dateformat usage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...