I'm getting UTC string dates that look like this "2015-10-17T00:00:00.000Z" and want to convert them to an NSDate in this format "October 12th 2015 11:19:12 am"
我得到的UTC字符串日期看起来像这个“2015-10-17T00:00:00.000Z”,并希望以这种格式将它们转换为NSDate“2015年10月12日上午11:19:12”
This is the route that I'm trying but I can't seem to get the right dateFormat.
这是我正在尝试的路线,但我似乎无法获得正确的dateFormat。
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = //can't seem to get this right
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString("2015-10-17T00:00:00.000Z")
2 个解决方案
#1
15
I think this should work
我认为这应该有效
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let localDate = formatter.dateFromString(date)
#2
3
This works for Swift 3.0 and latest Xcode [April 2017]
这适用于Swift 3.0和最新的Xcode [2017年4月]
let dateString = "2017-Jan-01 12:00:00.250"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-M-dd HH:mm:ss.SSS"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
let date = dateObj
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSXXXXX"
let currentDateTime = formatter.string(from: date!)
#1
15
I think this should work
我认为这应该有效
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let localDate = formatter.dateFromString(date)
#2
3
This works for Swift 3.0 and latest Xcode [April 2017]
这适用于Swift 3.0和最新的Xcode [2017年4月]
let dateString = "2017-Jan-01 12:00:00.250"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-M-dd HH:mm:ss.SSS"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
let date = dateObj
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSXXXXX"
let currentDateTime = formatter.string(from: date!)