Getting hour offsets for local time versus a target time zone in Swift
I am currently working on something that will display time in different time zones. However, you need to compare the user’s current time versus those at the target time zones to be accurate. This is what I figured out.
It’s easy to get the user’s local time.
let cal = Calendar(identifier: .gregorian) let date = Date() let hour = cal.component(.hour, from: date) let minute = cal.component(.minute, from: date) let second = cal.component(.second, from: date) print("\nLOCAL TIME: \(hour):\(minute):\(second)\n")
Now, you need to get the time in other time zone targets. Here is an example for London, England. A continuation from the code above.
let locale = TimeZone.init(identifier: "Europe/London") let comp = cal.dateComponents(in: locale!, from: date) print("LONDON: \(String(describing: comp.hour!)):\(String(describing: comp.minute!)):\(String(describing: comp.second!)), day: \(comp.day!)")
Excellent. Now, compute the difference between the user’s local time and the time in London.
// I am in Boston currently. print("London offset (modifier): \(comp.hour! - hour)") // 5
And there you have it. The difference is 5 hours ahead (it’s a positive value). If I were in London or that time zone, the difference would be 0. For someone like me who rarely dabbles in date work, this was a bit of discovered magic. For others, this post must be quite pedestrian and a waste of time. I apologize. But if I found a post like this earlier, I could have saved myself some time.