Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 764
Zhang Avatar asked Mar 25 '26 17:03

Zhang


1 Answers

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
like image 140
javimuu Avatar answered Mar 28 '26 19:03

javimuu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!