I have a bunch of different show times in a database and want to display the correct time based on the users time zone by creating an offset.
I\'m getting the users
If you want to convert a show time which is stored as a string in GMT, and you want to show it in the user's local time zone, you should not be manually adjusting the NSDate
/Date
objects. You should be simply using the appropriate time zones with the formatter. For example, in Swift 3:
let gmtTimeString = "5:00 PM"
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
formatter.timeZone = TimeZone(secondsFromGMT: 0) // original string in GMT
guard let date = formatter.date(from: gmtTimeString) else {
print("can't convert time string")
return
}
formatter.timeZone = TimeZone.current // go back to user's timezone
let localTimeString = formatter.string(from: date)
Or in Swift 2:
let formatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) // original string in GMT
let date = formatter.dateFromString(gmtTimeString)
formatter.timeZone = NSTimeZone.localTimeZone() // go back to user's timezone
let localTimeString = formatter.stringFromDate(date!)
I would use the dateByAddingTimeInterval function to add and subtract hours. Add a to the dateFormat string to print am or pm.
var showTimeStr = "00:00 PM" //show time in GMT as String
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm a"
let showTime = formatter.dateFromString(showTimeStr)
showTime.dateByAddingTimeInterval(3600) //Add number of hours in seconds, subtract to take away time
showTimeStr = formatter.stringFromDate(showTime)
Here is my final code, combined with b.Morgans answer. I believe it's all working now.
let offsetTime = NSTimeInterval(NSTimeZone.localTimeZone().secondsFromGMT)
var showTimeStr = "05:00 PM" //show time in GMT as String
let formatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"
let showTime = formatter.dateFromString(showTimeStr)
let finalTime = showTime?.dateByAddingTimeInterval(offsetTime) //Add number of hours in seconds, subtract to take away time
showTimeStr = formatter.stringFromDate(finalTime!)