How can I convert including timezone date in swift?

前端 未结 2 560
情歌与酒
情歌与酒 2020-12-07 18:04

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          


        
相关标签:
2条回答
  • 2020-12-07 18:30

    You can use :

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

    Hope this help you !

    0 讨论(0)
  • 2020-12-07 18:40

    Xcode 8 • Swift 3

    You need to escape 'T' and use the appropriate timezone symbol. Note that it will depend if your date string represents a UTC (zero seconds from GMT) time timezone with Z "XXXXX" or without it +00:00 "xxxxx":

    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:

    0 讨论(0)
提交回复
热议问题