StableUpper
StableUpper

Reputation: 173

Swift UTC TimeZone is not UTC

I have a question about Swift type TimeZone. I need to get a UTC0 time zone to format my Date object. I'm creating TimeZone object like this.

let utcTimeZone = TimeZone(abbreviation: "UTC")

But when created this object gives me GMT0 time zone. Is this possible to get UTC0 time zone in Swift? Also what is the difference between GMT (fixed) and GMT (GMT) offset 0 in playground?

Xcode 10.3 Playground enter image description here

Upvotes: 13

Views: 19807

Answers (3)

Santiago
Santiago

Reputation: 588

You can use this instead of UTC, in some device only setting UTC not working

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2020-01-23T11:55:00.000Z")

Upvotes: 2

Sweeper
Sweeper

Reputation: 270860

Technically, there are really subtle differences between UTC and GMT (GMT could mean UT1), but the designers of the API thought they are practically the same (which they are), so they made this true:

TimeZone(identifier: "UTC") == TimeZone(identifier: "GMT")

They both represent a timezone with a constant offset of 0.

If you just want to show the letters "UTC" in some output text, use a DateFormatter:

let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss 'UTC'"
print(formatter.string(from: Date()))

Or better yet, use a ISO8601DateFormatter, which adds a Z to the end of the date to indicate that the date time is in UTC:

let formatter = ISO8601DateFormatter()
formatter.timeZone = TimeZone(identifier: "UTC")
print(formatter.string(from: Date()))

Also what is the difference between GMT (fixed) and GMT (GMT) offset 0 in playground?

The former comes from the Swift TimeZone class, and the latter comes from the Objective-C NSTimeZone class. One is the bridged version of the other. From the docs of NSTimeZone,

use NSTimeZone when you need reference semantics or other Foundation-specific behavior.

Upvotes: 29

Ben Rasmussen
Ben Rasmussen

Reputation: 297

I've been there, according to google

There is no time difference between Coordinated Universal Time and Greenwich Mean Time

In other words, GMT is (basically) UTC, so you already have it!

offset 0 is referring to the timezones offset from UTC/GMT, which is 0, and would be potentially something like 240 if you were in EST (depending on if it's in minutes, hours, milliseconds etc.).

fixed on your second line means it's GMT and the offset data is potentially immutable. I wouldn't know without the playground open but I'd try changing the timezone after instancing that and see how if the offset can be changed post assignment.

Upvotes: 2

Related Questions