Getting the current day, hour, minute etc for the users current location is fairly straight forward using a function like this, so long as you have UTC data:
func getHourForDate(_ date: Date?)-> String{
guard let date = date else {return "error"}
//initialize formatter
let formatter = DateFormatter()
//set format to 12 hour clock with am/pm
formatter.dateFormat = "h a"
//return formatting string
return formatter.string(from: date)
}
The problem I ran into is that when I try to parse data from locations around the world, that function only gives me the time based on my own location. OpenWeather seems to provide some data to get around this. Take a look at a couple parameters from the weather response I've created:
struct WeatherResponse: Codable {
let timezone: String
let timezone_offset: Int
}
So I have a string that gives me data like "Atlantic", and an offset such as "-14400." The problem is that I don't know how to apply any of this data. It doesn't seem correct to simply subtract timezone_offset from the UTC time provided by the API. I tried something like the code provided below, but it only seemed to work when I ran the app on my phone, using my actual current location, and not when I tried simulating other locations around the world as my current location:
//get the difference of my current location timezone offset and the offset of each json response
//(this should cancel out any offset for my current location)
let timezoneDifference = currentLocationTimezoneOffset - timezone_offset
//subtract the offset from the hour date provided by the json
let offset = utcFromJson - timezoneDifference
//pass the offset into the function to return a formatted date string
let hourLabel.text = getHourForDate(Date(timeIntervalSince1970: TimeInterval(offset)
I hope this question is straight forward or that I didn't omit any useful information. Any help is appreciated, thanks!
CodePudding user response:
you could try something simple, like this example code, to get the time at the "other" location:
let timeHere = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL dd, hh:mm:ss a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: response.timezone_offset) // <-- here
let timeThere = dateFormatter.string(from: timeHere)
print("timeHere: \(timeHere) timeThere: \(timeThere) \n")