I get nil when using NSDateFormatter in swift

本小妞迷上赌 提交于 2019-12-19 11:29:48

问题


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 ?


回答1:


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.




回答2:


I know that it's to late, but

dateFormatter.dateFormat = "YYYY-MM-DD'T'HH:mm:ss.sss'Z'"

should be

dateFormatter.dateFormat = "YYYY-MM-DD'T'HH:mm:ss.SSS'Z'"

because,

1)

ss - seconds
SSS - fractional second

sss != SSS

2)

  T -> 'T'; S -> 'S'

And nice tutorial



来源:https://stackoverflow.com/questions/28750048/i-get-nil-when-using-nsdateformatter-in-swift

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