Khushbu Desai Khushbu Desai - 3 years ago 189
Swift Question

How can i find GMT from given date

I have a date like 2017-08-12 11:30:00 and i want to display Date as

sat, 12 aug 2017 11:30 am( 06:00 GMT )
i get
sat, 12 aug 2017 11:30 am
using following code

let myDate = "2017-08-12 11:30:00"

let date = myDate.date(format: .custom("yyyy-MM-dd HH:mm:ss"))
let strDate = date?.string(format: .custom("EEE, dd MMM yyyy hh:mm a"))
let localDate = strDate?.date(format: .custom("EEE, dd MMM yyyy hh:mm a"))
let strLocalDate = localDate?.string(format: .custom("EEE, dd MMM yyyy hh:mm a"))


but how can i find GMT ?

for GMT i have also tried
formatter.timeZone = TimeZone(identifier:"GMT")
but it didn't work.

please help,
Thanks!

Answer Source

Try this code.I have tested, it is working for me in swift3.0.

        let myDate = "2017-08-12 11:30:00"
        let localDateFormat = DateFormatter()
        localDateFormat.dateFormat = "YYYY-mm-dd hh:mm:ss"
        let localDate = localDateFormat.date(from: myDate)
        localDateFormat.dateFormat = "EEE, dd MMM yyyy hh:mm a"
        let myNewDate = localDateFormat.string(from: localDate!)
        print(myNewDate)
        //GMT Date
        let gmtDateFormat = DateFormatter()
        gmtDateFormat.dateFormat = "HH:mm a"
        gmtDateFormat.timeZone = NSTimeZone(abbreviation: "GMT")! as TimeZone
        let gmtDateString = gmtDateFormater.string(from: localDate!)
        print(gmtDateString)

        print("time:\(myNewDate)(\(gmtDateString))")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download