SpaceX
SpaceX

Reputation: 2890

Convert date string of one time zone to date object in local time Swift

I want dateString in this format "2016-12-22T08:00:00-08:00" to be converted to date object in users local time for example 2016-12-22 21:30:00 +0530 when the users time is +05:30 from UTC

OR

I want dateString in this format "2016-12-22T08:00" which is PST time to be converted to date object in users local time for example 2016-12-22 21:30:00 +0530 when the users time is +05:30 from UTC or 2016-12-22 16:00:00 +0000 when the users time is 00:00 from UTC

When I try the below code and print dateObject it prints Optional(2016-12-22 02:30:00 +0000) but I want 2016-12-22 21:30:00 +0530 since my local time is +05:30 from UTC.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-08:00"
dateFormatter.timeZone = NSTimeZone.local

let dateString = "2016-12-22T08:00:00-08:00"
let dateObject = dateFormatter.date(from: dateString)
print("dateObject \(dateObject1)")

Upvotes: 1

Views: 2489

Answers (1)

rmaddy
rmaddy

Reputation: 318814

Fix your dateFormat to:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"

Remove the timeZone line. It's not needed since your date string specifies its own timezone.

dateFormatter.timeZone = NSTimeZone.local // remove this line

Now your code works fine.

"But wait, the output of print(dataObject) isn't what I want"

Yes it is. Like thousands before you, you misunderstand the output of printing a Date object.

If you wish to view a Date in the local timezone, in a given format, use a DateFormatter to convert the Date into a String. You will get the current, local timezone by default.

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
let newString = dateFormatter.string(from: dateObject)
print(newString)

And you get just what you wanted.

Upvotes: 2

Related Questions