naohide naohide - 6 months ago 24
iOS Question

How can I convert including timezone date in swift?

I want to convert

2015-08-14 16:02

I tried below, but it could't execute well(returned nil).

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)

How can I convert this date format?


You need to escape T and use "xxx" for "-04:00":

let dateString = "2015-08-14T20:02:25-04:00"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxx"
if let dateFromString = formatter.dateFromString(dateString) {
    formatter.dateFormat = "yyyy-MM-dd HH:mm"
    let stringFromDate = formatter.stringFromDate(dateFromString)

If you need some reference you can use this:

enter image description here