iosswifttimezonensdategmt

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.


Solution

  • 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")