I'm new to programming and trying to start my journey by learning Swift. Currently I'm working on a weather app which I'm developing for learning purposes.
I'm using the openweathermap.org API to get the weather and solar data.
Right now I'm fully able to parse JSON and use the info. The only problem that I'm facing is that Swift calculates the sunset and sunrise time based on my local timezone, which I don't want.
I live in Amsterdam. If I want to look up the sunset and sunrise in New York, I should get the sunset and sunrise information based on New York's local time and not mine.
func sunTimeConverter(unixTimeValue: Double) -> String {
let dateAndTime = NSDate(timeIntervalSince1970: unixTimeValue)
let dateFormater = DateFormatter()
dateFormater.dateStyle = .none
dateFormater.timeStyle = .short
dateFormater.timeZone = TimeZone(abbreviation: "GMT")
dateFormater.locale = Locale.autoupdatingCurrent
let currentdateAndTime = dateFormater.string(from: dateAndTime as Date)
return currentdateAndTime
}
let sunSetFromJSON = jsonObject["sys"]["sunset"].doubleValue
weatherDataModel.citySunSet = sunTimeCoverter(unixTimeValue: sunSetFromJSON)
this is the JSON object :
{
"main" : {
"humidity" : 93,
"temp_max" : 285.14999999999998,
"temp_min" : 284.14999999999998,
"temp" : 284.39999999999998,
"pressure" : 1020
},
"name" : "Beverwijk",
"id" : 2758998,
"coord" : {
"lon" : 4.6600000000000001,
"lat" : 52.479999999999997
},
"weather" : [
{
"id" : 701,
"main" : "Mist",
"icon" : "50n",
"description" : "mist"
}
],
"clouds" : {
"all" : 75
},
"dt" : 1510260900,
"base" : "stations",
"sys" : {
"id" : 5204,
"message" : 0.0201,
"country" : "NL",
"type" : 1,
"sunset" : 1510242952,
"sunrise" : 1510210438
},
"cod" : 200,
"visibility" : 4500,
"wind" : {
"speed" : 3.6000000000000001,
"deg" : 220
}
}
You need to slightly change your method and add the timezone you want to display:
func sunTimeCoverter(unixTimeValue: Double, timezone: String) -> String {
let dateAndTime = NSDate(timeIntervalSince1970: unixTimeValue)
let dateFormater = DateFormatter()
dateFormater.dateStyle = .none
dateFormater.timeStyle = .short
dateFormater.timeZone = TimeZone(abbreviation: timezone)
dateFormater.locale = Locale.autoupdatingCurrent
let currentdateAndTime = dateFormater.string(from: dateAndTime as Date)
return currentdateAndTime
}
So for NY, you would call it like this: (You would need to know the timezone from openweathermap.org
)
let sunSetFromJSON = jsonObject["sys"]["sunset"].doubleValue
weatherDataModel.citySunSet = sunTimeCoverter(unixTimeValue: sunSetFromJSON, timezone: "UTC-05:00")