我想转换2015-08-14T20:02:25-04:00到2015-08-14 16:02
我尝试下面,但它不能执行得很好(返回零).
我尝试下面,但它不能执行得很好(返回零).
let d = "2015-08-14T20:02:25-04:00" let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ" let date: NSDate? = formatter.dateFromString(d)
如何转换这个日期格式?
解决方法
Xcode 8•Swift 3
let dateString = "2015-08-14T20:02:25-04:00" let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx" if let dateFromString = formatter.date(from: dateString) { formatter.dateFormat = "yyyy-MM-dd HH:mm" let stringFromDate = formatter.string(from: dateFromString) }
您需要退出’T’,并使用“xxxxx”作为“-04:00”:
let dateString = "2015-08-14T20:02:25-04:00" let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx" if let dateFromString = formatter.dateFromString(dateString) { formatter.dateFormat = "yyyy-MM-dd HH:mm" let stringFromDate = formatter.stringFromDate(dateFromString) }
如果你需要一些参考,你可以使用: