我有以下格式的日期字符串:
2016-06-20T13:01:46.457+02:00
我需要将其更改为以下内容:
20/06/2016
以前,我一直使用此库-> SwiftDate来操作日期,但现在不起作用。
我也尝试过类似的东西:
let myDate = self.dateNoteDict[indexPath.row]! let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx" let date = dateFormatter.dateFromString(myDate) print("date -> \(date)")
但这不起作用。我能怎么做?
提前致谢。
具有小数秒和时区的标准ISO8601日期格式为
yyyy-MM-dd’T’HH:mm:ss.SSSZ
let myDate = "2016-06-20T13:01:46.457+02:00" let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") // edited dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let date = dateFormatter.dateFromString(myDate)! dateFormatter.dateFormat = "dd/MM/yyyy" let dateString = dateFormatter.stringFromDate(date)
斯威夫特3:
let myDate = "2016-06-20T13:01:46.457+02:00" let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") // edited dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let date = dateFormatter.date(from:myDate)! dateFormatter.dateFormat = "dd/MM/yyyy" let dateString = dateFormatter.string(from:date)
在macOS 10.13+中,iOS 11+ ISO8601DateFormatter是输入格式化程序的替代方法
ISO8601DateFormatter
let myDate = "2016-06-20T13:01:46.457+02:00" let inputFormatter = ISO8601DateFormatter() inputFormatter.formatOptions = [.withFullDate, .withFullTime, .withFractionalSeconds] let date = dateFormatter.date(from:myDate)! let outputFormatter = DateFormatter() outputFormatter.locale = Locale(identifier: "en_US_POSIX") outputFormatter.dateFormat = "dd/MM/yyyy" let dateString = dateFormatter.string(from:date)