[英]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 ?
我究竟做错了什么 ?
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. 因为您的字符串中有一个
T
,所以您需要“转义”它并说,它不应该影响日期的格式。
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
. 就像您看到的一样,我将
sss
更改为SSS
(代表毫秒),还将YYYY
更改为小写yyyy
,与DD
相同。 You have to be really carefully, when to use upper and lowercase letters in your Dateformat-strings. 在Dateformat字符串中使用大写和小写字母时,必须非常小心。
Check @HotLicks link in the comments which shows a great overview of the dateformat usage. 检查注释中的@HotLicks链接,该链接很好地概述了dateformat的用法。
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) 1)
ss - seconds
SSS - fractional second
sss != SSS
2) 2)
T -> 'T'; S -> 'S'
And nice tutorial 和不错的教程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.