Converting date between timezones swift

I have a date stored on my online server database which is in GMT. I load the date and convert it to the user’s timezone using the following code :

 if let messagedate = oneitem["timestamp"] as? String {
     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
     let date = dateFormatter.dateFromString(messagedate)
     let source_timezone = NSTimeZone(abbreviation: "GMT")
     let local_timezone = NSTimeZone.systemTimeZone()
     let source_EDT_offset = source_timezone?.secondsFromGMTForDate(date!)
     let destination_EDT_offset = local_timezone.secondsFromGMTForDate(date!)
     let time_interval : NSTimeInterval = Double(destination_EDT_offset - source_EDT_offset!)


     let final_date = NSDate(timeInterval: time_interval, sinceDate: date!)
     curr_item.date = final_date
 }

Now I need to convert the date back to GMT in order to communicate it to the server, however I’m not sure how to convert it back to GMT.

  • In-App Purchases: Crash when view disappear
  • How can I change constraints priority in run time
  • Difference between properties and variables in iOS header file?
  • Strict Type Checking in Objective-C Part 2
  • How to use c++ and objective-c together in XCode 4.2
  • UIImageView with Aspect Fill inside custom UITableViewCell using AutoLayout
  • 4 Solutions Collect From Internet About “Converting date between timezones swift”

    Couldn’t you just use your data formatter again with a different time zone and convert it? Such as

    dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
    let gmtDate = dateFormatter.dateFromString(string: "your old date as string here")
    

    about 50 times more effecient

    Using the offset from GMT is about 22 times more effecient.

    extension Date {
        func convertToLocalTime(fromTimeZone timeZoneAbbreviation: String) -> Date? {
            if let timeZone = TimeZone(abbreviation: timeZoneAbbreviation) {
                let targetOffset = TimeInterval(timeZone.secondsFromGMT(for: self))
                let localOffeset = TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT(for: self))
    
                return self.addingTimeInterval(targetOffset - localOffeset)
            }
    
            return nil
        }
    }
    

    Since NSDate is always in GMT/UTC the time zone only becomes relevant when displaying it to, or getting it from, the user. Just always assume it’s UTC internally, convert it for the user (by setting it on the NSDateFormatter) as necessary, and you no longer have to worry about the problem.

    I suggest

    • you set the GMT timezone on your dateFormatter to get back directly a NSDate in UTC (having only NSDates in UTC is a good practice)
    • when you need to display it you use another NSDateFormatter with the local time zone set on it (it is by default)
    • when you need to send a date to your server, you use dateFormatter again to generate a string