Zhang
Zhang

Reputation: 11607

iOS Date timezone conversion not working

In my playground, I'm testing conversion of date time but it doesn't seem to be converting:

import UIKit

let dateString = "2017-12-01 10:00:00 +0000"

print("original date = \(dateString)")

var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.timeZone = TimeZone(identifier: "Asia/Shanghai")

if let date = formatter.date(from: dateString) {
    print("converted date = \(date)")
}
print("test")

The output is:

original date = 2017-12-01 10:00:00 +0000
converted date = 2017-12-01 10:00:00 +0000
test

I'm expecting the converted date to say something like 2017-12-01 18:00:00 +0800 (since Shanghai is 8 hours ahead of UTC 00:00:00)

Upvotes: 3

Views: 1443

Answers (2)

javimuu
javimuu

Reputation: 1859

Please try this:

let dateString = "2017-12-01 10:00:00 +0000"

print("original date = \(dateString)")

var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
formatter.timeZone = TimeZone.init(abbreviation: "UTC")

if let date = formatter.date(from: dateString) {
    formatter.timeZone = TimeZone(identifier: "Asia/Shanghai")
    let localTime = formatter.string(from: date)
    print(localTime)
}
print("test")

Output:

original date = 2017-12-01 10:00:00 +0000
2017-12-01 18:00:00 +0800
test

Upvotes: 4

Kay Weng
Kay Weng

Reputation: 73

GMT: formatter.timeZone = TimeZone(abbreviation: NSTimeZone.local.abbreviation()!)

UTC: formatter.timeZone = TimeZone(abbreviation: NSTimeZone.default.abbreviation()!)

To display local datetime, i use the GMTTimeZone.

Upvotes: 0

Related Questions