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
.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With