简体   繁体   中英

dateFromString gives nil, swift

I am trying to create a NSDate object from a String. 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. 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). Since you're using 24 hours format ( 16:.. ), you need to use specifier HH instead, eg:

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

Also:

  • avoid using explicit unwrapping of optionals ( ! ), use eg optional binding ( if let ... ) instead, and
  • consider migrating to Swift 3: it's now official.

Eg (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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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