How to Convert MYSQL DateTime to NSDate - Swift [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-13 09:59:59

问题


"2015-06-30T17:30:36.000Z" is an example of DateTime value in MySQL. How to convert it to NSDate in Swift?

Below is my code but it does not work

var sqlDateFormatter = NSDateFormatter()
sqlDateFormatter.dateFormat = "yyyy’-‘MM’-'dd’T'HH’:'mm’:'ss'Z’"
self.whenPublished = self.sqlDateFormatter.dateFromString("2015-06-30T17:30:36.000Z")

回答1:


You just need to add the milliseconds thats it is missing at the end of your dateFormat string. Try like this:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let string = "2015-06-30T17:30:36.000Z"
if let date = dateFormatter.date(from: string) {
    print(date)   // "2015-06-30 17:30:36 +0000"
}

Note: You need to use regular single cote ' instead of curved cote



来源:https://stackoverflow.com/questions/31331265/how-to-convert-mysql-datetime-to-nsdate-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!