I am making an app which among other things, it determines the sunset and sunrise. Nevertheless I've found some difficulties to get them using the user's local time. Therefore, I would like to know: how can I get the user's time zone in Swift?
The coordinates of my test location (Puerto Vallarta, Mex) that I load in the iPhone simulator are these:
Latitude: 20.61 Longitude: -106.23
The next is part of my code to determine the sunrise and the sunset of any location in the world:
//First we get the sunrise time.
let sunriseDate = Date(timeIntervalSince1970: sunriseValue.doubleValue)
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .medium
formatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
formatter.dateFormat = "HH:mm:ss"
let sunrise = formatter.string(from: sunriseDate)
print(sunrise)
//Second, we get the sunset time
let sunsetDate = Date(timeIntervalSince1970: sunsetValue.doubleValue)
let sunset = formatter.string(from: sunsetDate)
print(sunset)
And this is what I get from the console:
Sunrise: 13:08:12 Sunset: 00:21:22
This is more than evident that the printed sunrise and sunset correspond to the UTC, nevertheless I haven't found any direct information that could help me to get the user's local time, wherever that person is.
Basically the sunrise and sunset that you see in the code above I got it from an API (openweather) from which I got their values in unix time (which I converted to date and time using this link . Now I see that I effectively got the correct sunset and sunrise but in UTC format, now I'm missing one step to go from UTC to local time.
So, in summary, I got:
from API: time in unix time (e.g. sunrise = 1541855294; sunset = 1541895681;), extract from it the time using DateFormatter() (see code above) and I got the UTC time (formatter.dateFormat = "HH:mm:ss").
I hope that with this modification the question is more clear now.
That's why I wanted to ask you if you cand lend me a hand with this, please :)
Thanks in advance and I apologize for any misunderstanding!