简体   繁体   English

dateFromString给出nil,迅速

[英]dateFromString gives nil, swift

I am trying to create a NSDate object from a String. 我正在尝试从字符串创建NSDate对象。 I have hardcoded my string for you to see. 我已经对我的字符串进行了硬编码,以供您查看。 When i am calling dateFromString on my string, the result will be nil, and i am getting an exception because of unwrapping a nil. 当我在字符串上调用dateFromString时,结果将为nil,并且由于展开nil而导致异常。 I have pasted my code below. 我在下面粘贴了我的代码。

Any ideas how to do this the right way? 任何想法如何正确地做到这一点?

Thank you very much! 非常感谢你!

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"

    let timeToParse = "19/10/2016 16:10"

    let date = dateFormatter.dateFromString(timeToParse)
    //date = nil?

    dateFormatter.dateFormat = "yyyy/MM/dd hh:mmZZZ"
    let dateWithUTC = dateFormatter.stringFromDate(date!)

You've supplied hh for hours, but this expects a format with 1-12 hours (with at least 2 digits). 您已经提供了hh几个小时的信息,但这需要1-12个小时的格式(至少2位数字)。 Since you're using 24 hours format ( 16:.. ), you need to use specifier HH instead, eg: 由于您使用的是24小时制( 16:.. ),因此需要使用说明符HH代替,例如:

dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"

Also: 也:

  • avoid using explicit unwrapping of optionals ( ! ), use eg optional binding ( if let ... ) instead, and 避免使用显式解开可选的( ! ),而是使用例如可选的绑定( if let ... ),以及
  • consider migrating to Swift 3: it's now official. 考虑迁移到Swift 3:它现在是正式的。

Eg (Swift 3) 例如(Swift 3)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm"

let timeToParse = "19/10/2016 16:10"

if let date = dateFormatter.date(from: timeToParse) {
    print(date) // 2016-10-19 16:10:00 +0000
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM