3

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
  }
}
Joseph
  • 89
  • 9
  • First create a date using the unixTimeValue. `Date(timeIntervalSince1970: unixTimeValue)` – Leo Dabus Nov 09 '17 at 21:58
  • Then use date formatter to show your local time – Leo Dabus Nov 09 '17 at 21:58
  • 2
    The only way to show a city's sunset/sunrise times in that city's timezone is to determine the city's timezone. Get the timezone from the data and use that. – rmaddy Nov 09 '17 at 22:01
  • You're using `TimeZone(abbreviation: "GMT")`. You need `TimeZone(abbreviation: "EST")` if you're looking for NY. If you want to make it dynamic then you have to get that information from the device. That still provide the granularity down to specific cities. – Aaron Nov 09 '17 at 22:03
  • i'm not specifically looking for New York's timezone. The idea behind the app is to let users search for cities around the world. – Joseph Nov 09 '17 at 22:05
  • You're post lacks a specific question. You might want to edit it to clarify exactly what you're asking to avoid ambiguity in the community's comments and/or answers. – Aaron Nov 09 '17 at 22:08
  • @Joseph the time it is UTC. Just convert the unix time to date and use date formatter to show the time. Thats all you need – Leo Dabus Nov 09 '17 at 22:09
  • @Aaron The question is quite clear. *"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."*. – rmaddy Nov 09 '17 at 22:10
  • No it's not. I don't see a question there nor does it say _for example_. It's a statement. A clear question would be _how do I get sunset and sunrise time on a city-by-city basis?_ – Aaron Nov 09 '17 at 22:11
  • The api will return the json based on the request. The Unix time it is all You need to get the Date. You just need to use the corresponding timezone of the city you used to request the data. – Leo Dabus Nov 09 '17 at 22:23
  • You should also post the code regarding your api request – Leo Dabus Nov 09 '17 at 22:26

2 Answers2

0

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")
Robert D. Mogos
  • 900
  • 7
  • 14
  • The timezone needs to come from the data, not hardcoded. – rmaddy Nov 09 '17 at 22:06
  • Of course, but I don't know what was inside of his jsonObject. It was just an example – Robert D. Mogos Nov 09 '17 at 22:07
  • It seems that people are complaining about openweathermap.org that the timezone is not included: https://openweathermap.desk.com/customer/portal/questions/17126033-sunrise-sunset – Robert D. Mogos Nov 09 '17 at 22:15
  • i guess i must figure it out by using, latitude and longitude data from the api! – Joseph Nov 09 '17 at 22:19
  • Are your forced to use openweathermap ? You can check [darksky](https://darksky.net/dev/docs) or [weatherbit](https://www.weatherbit.io/api/weather-current) which gives you the timezone so it's easier – Robert D. Mogos Nov 09 '17 at 22:21
  • thanks Robert :D, actually as i mentioned in my intro text, i started programming like 3 months ago, like 16 hours a day, 6 days a week. as i'm learning i don't want to be lazy from the beginning! so i try and try harder every day to learn more and complex stuff, the only reason i wanna stick with the openweathermap.org api is, i want to keep my code clean and tight! and i noticed i'm learning more and more, for example i just posted my first stackoverflow topic :D – Joseph Nov 09 '17 at 22:24
  • Gotcha. Your question is tricky because you ask on how to convert a unix time into a date string with a specific timezone and not your own timezone, which I gave you the answer. But, in your specific case with openweathermap is impossible since you don't have the access to the timezone. So I would 1. change the question or 2. accept the answer and ask another question on how to get the timezone from lat/lng or city name. – Robert D. Mogos Nov 09 '17 at 22:32
  • Looking at the docs for the API, the 5 day forecast includes both timezone of the location as well as the sunrise and sunset data. – rmaddy Nov 09 '17 at 22:44
  • Only the XML response, not the JSON – Robert D. Mogos Nov 09 '17 at 22:47
  • I solved it by using a switch statement ! openweathermap.org api provides the country initials so i created a switch! func findOutTimeZone(countryInit: String) -> String { switch countryInit { case "US": return "GMT-07:30", i know it's not a real life solution! but at least im able to work around the info that im getting from openweather api, – Joseph Nov 09 '17 at 23:13
  • @Joseph forget about this approach. There is multiple timezones in US. You could search the timezone using the city, not the country alone. – Leo Dabus Nov 09 '17 at 23:39
0

You can get the time zone of the place based on this answer. And based on the timezone, you can calculate the sunset and sunrise time for the place.

vishalwaka
  • 89
  • 1
  • 12