简体   繁体   English

将日期字符串转换为NSDate

[英]Convert date string to NSDate

I've this string: "2016-10-08 00:20:00.000000". 我有这个字符串:“ 2016-10-08 00:20:00.000000”。 And I need it as an NSDate (Date for swift 3) object. 我需要它作为NSDate(快速3的日期)对象。

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, 或更改dateformatter之类的,

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

And hh should be capital for 24 - hour format!!!! 而且hh应该是24小时格式的大写字母!!!! like HH ! 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")
}

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

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