简体   繁体   中英

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.

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 !

If you want use nano seconds your code must be :

let formatterJsonDate = DateFormatter()
formatterJsonDate.dateFormat = "yyy-MM-dd hh:mm:ss.SSSS"
if let myDate = formatterJsonDate.date(from: "2016-10-08 00:20:00.000000")  {
    print(myDate)
} else {
    print ("Invalid Date")
}

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