Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 462
Alk Avatar asked Jul 28 '16 16:07

Alk


People also ask

How do I change timeZone in Swift?

Standard Approach, using a DateFormatter() 🗓current timeZone. This will be set to . current by default, but it is important to note in case you need to set anything other that the current timeZone that you exist in. Also notice that the date format being set has the 'T' and Z characters in it.

How do I get todays date in Swift?

Get current time in “YYYY-MM–DD HH:MM:SS +TIMEZONE” format in Swift. This is the easiest way to show the current date-time.


1 Answers

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") 
like image 196
Amloelxer Avatar answered Sep 19 '22 01:09

Amloelxer