Search code examples
iosswiftdateswift3nsdate

Convert Specific Date String to Swift 3 Date While Adjusting for TimeZone


I know how to convert a datestring in this format (2016-11-02 05:45:05.000000) to a date in Swift3 but I can't figure out why the time that spits back out from the print command is off from the original by so much? From reading it might be setting it to a different timezone, but if that is the case how do I reset it back to the original time?

It incorrectly looks like this below for the sample time I gave above. Notice it's off by many hours.

2016-11-02 12:45:05 +0000

Here is my code below and the image showing the console print commands.

let dateString : String       = task["created"]!.asDictionary!["date"]!.asString!

                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSSS"

                let date = dateFormatter.date(from: dateString)

                print(name)
                print("\(id)")
                print(desc)
                print(dateString)
                print(date!)

enter image description here

Please refer to the image.


Solution

  • You need to set the timezone:

    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)