简体   繁体   English

在Swift中使用NSDateFormatter时我得到零

[英]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.

相关问题 NSDateFormatter在swift和iOS SDK 8.0中返回nil - NSDateFormatter returns nil in swift and iOS SDK 8.0 Swift:NSDateFormatter dateFromString在设备上返回nil - Swift: NSDateFormatter dateFromString returns nil on devices NSDateFormatter自动获取dateFormat(Swift 2) - NSDateFormatter automatically get dateFormat (Swift 2) NSDate为零时,NSDateFormatter返回(空)字符串 - NSDateFormatter return (null) string when NSDate is nil 在 xcode/swift 中使用位置管理器来获取用户的当前位置时,我得到的值为 nil。 有什么建议么? - When using location manager, in xcode/swift, to get a user's current location, I get a value of nil. Any suggestions? 为什么我不能使用NSDateFormatter dateFromString从NSString获取Year? - Why can I not get the Year from a NSString using NSDateFormatter dateFromString? 使用情节提要板时,IBoutlets迅速消失 - IBoutlets nil in swift when using storyboards Swift-使用&#39;as!时为零! 字典 <String, AnyObject> &#39; - Swift - Nil when using 'as! Dictionary<String, AnyObject>' Swift NSDateFormatter 未使用正确的语言环境和格式 - Swift NSDateFormatter not using correct locale and format 在iPad3上运行应用程序时,在模拟器上没有变量,但变量没有显示。 斯威夫特4 - I get nil on a variable when running app on iPad3 but not on simulator. Swift 4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM