Search code examples
iosswiftnsdatensdateformatter

Convert date string to NSDate


I've this string: "2016-10-08 00:20:00.000000". And I need it as an NSDate (Date for swift 3) object.

I've tried with the following:

let formatterJsonDate = DateFormatter()
formatterJsonDate.dateFormat = "yyy-MM-dd hh:mm:ss"

print(formatterJsonDate.date(from: "2016-10-08 00:20:00.000000"))

I always return nil value. What's wrong? I guess it's something about the date format.


Solution

  • Your date format and your time string should be same. In your case it should be like,

     let formatterJsonDate = DateFormatter()
     formatterJsonDate.dateFormat = "yyy-MM-dd HH:mm:ss"
    
     print(formatterJsonDate.date(from: "2016-10-08 00:20:00"))
    

    Or change dateformatter like,

      "yyyy-MM-dd HH:mm:ss.SSSSSS"
    

    And hh should be capital for 24 - hour format!!!! like HH!