Search code examples
iosswiftdateepoch

Date(timeIntervalSince1970:) returns 2 different results


I am getting some results from a weather API and one of that is date in epoch time stamp.

I found that converting with Date(timeIntervalSince1970:) I get the right date

I am using the specific number --> 1501452000 and I get 2 results on Playground

1) Jul 31,2017,12:00AM. -- when --> let date = Date(timeIntervalSince1970: 1501452000)

2) 2017-07-30 22:00:00 +0000 when --> print(date)

API results are : "time_epoch": 1501452000, "time": "2017-07-30 23:00",

By checking the rest of my results they are matching with the rest of the API results....... but when I convert 1501452000 -> to date I don't get the correct Hour 23:00 but 22:00 !

Any idea what is happening ? is it wrong the API( I don't think so ) or the way I am converting it?

Thanks a lot


Solution

  • The timeIntervalSince1970 initializer sets up the time in the UTC timezone, while your API might be sending dates in GMT. When you are using print(data), you have different results, because if you are not using a DateFormatter to generate the String format of the Date object, it uses your devices current settings when formatting the Date object.

    A Date object represents an absolute point in time, but when you are printing it with a DateFormatter, it gets converted into a location/time zone specific, relative representation. You just have to set up your DateFormatter to match the time zone settings of your API and you will see the dates correctly printed.