Search code examples
iosswifttimestampnsdateformatter

How to format a date using timezone in Swift?


I have checked other questions but none of them helped me much.

I have following string:

let dateString = "2018-04-29T21:00:00.000Z"

I have successfully converted it to date using the following:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let convertedDate = dateFormatter.date(from: dateString)

But now I only want the time "hh:mm a" using timezone such as "+8". I have tried following way but it's not working:

let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC+8")
dateFormatter.dateFormat = "hh:mm a"
let requiredTime = dateFormatter.string(from: convertedDate!)

Can anyone help me to overcome this problem?


Solution

  • The format you want is hh:mm a Z, which will provide the +0800.

    You want to create a TimeZone which +8 hours from GMT, normally I prefer to use the appropriate abrivations (ie AET), but I guess if you don't have that, you can create a TimeZone using secondsFromGMT, for example...

    let tz = TimeZone(secondsFromGMT: 8 * 60 * 60)
    let toFormatter = DateFormatter()
    toFormatter.timeZone = tz
    toFormatter.dateFormat = "hh:mm a Z"
    let requiredTime = toFormatter.string(from: convertedDate!)
    

    Which based on your example data, will produce a value of...

    05:00 AM +0800