你好,我有一本字典
self.publishedAt = dictionary["publishedAt"] as? NSString
在其中我得到日期“ 2017-01-27T18:36:36Z ”。我想将其转换为可读格式: dd-MM-yyyy hh:mm:ss 。我尝试通过
let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy hh:mm:ss" let date = dateFormatter.date(from: (self.publishedAt as? String)!) print("EXACT_DATE : \(date)")
但是变得零。:(
以简单格式获取日期的正确方法是什么?
您需要输入格式将ISO8601字符串转换为日期,并且需要输出格式将日期转换回字符串:
let string = "2017-01-27T18:36:36Z" let dateFormatter = DateFormatter() let tempLocale = dateFormatter.locale // save locale temporarily dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let date = dateFormatter.date(from: string)! dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" dateFormatter.locale = tempLocale // reset the locale let dateString = dateFormatter.string(from: date) print("EXACT_DATE : \(dateString)")