How can I convert including timezone date in swift

2019-01-17 00:47发布

I want to convert 2015-08-14T20:02:25-04:00 to 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?

2条回答
再贱就再见
2楼-- · 2019-01-17 01:23

You can use :

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"

Hope this help you !

查看更多
放我归山
3楼-- · 2019-01-17 01:34

Xcode 8 • Swift 3

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

let dateString = "2015-08-14T20:02:25-04:00"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
if let date = formatter.date(from: dateString) {
    formatter.dateFormat = "yyyy-MM-dd HH:mm"
    let string = formatter.string(from: date)
    print(string)
}

If you need some reference you can use this:

enter image description here

查看更多
登录 后发表回答