How to convert UTC date to local and local to UTC?

I want to convert the date from local to UTC and UTC to Local.

For example, April 1, 2015, 12:00 PM - UTC, then

April 1, 2015, 5:30 pm is local to me, but I get the opposite from him.

let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"[![enter image description here][1]][1]
dateFormatter2.timeZone = NSTimeZone.local
let date2 = dateFormatter2.date(from: "2015-04-01T12:00:00")


dateFormatter2.timeZone = NSTimeZone(name: "UTC")! as TimeZone
let date3 = dateFormatter2.date(from: "2015-04-01T12:00:00")

I get April 1, 2015, 5:30 pm in UTC and April 1, 2015, 12:00 as a local

enter image description here

+4
source share
3 answers

finally it worked for me

let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
        let date = dateFormatter.date(from: "2015-04-01 12:00:00")
        print("UTC time",date!)

        dateFormatter.timeZone = NSTimeZone.local
        let timeStamp = dateFormatter.string(from: date!)

        print("Local time",timeStamp)
+2
source

The local time zone is always based on the default setting for your application.

From Apple documentation

Returns an object that forwards all messages to the default time zone for the current application.

NSTimeZone.system. , , iOS.

0

Try the following:

let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter2.timeZone = NSTimeZone.local
dateFormatter2.locale = Locale(identifier: "en_US_POSIX")
let date2 = dateFormatter2.date(from: "2015-04-01T12:00:00")


dateFormatter2.timeZone = TimeZone(identifier: "UTC")
let date3 = dateFormatter2.date(from: "2015-04-01T12:00:00")
0
source

Source: https://habr.com/ru/post/1685664/


All Articles