0

I want to store some data as a dictionary in my app relative to the date this data was created. It should look something like this:

// hours
[ 17:00 - 18:00 : 34.5,
  18:00 - 19:00 : 41.2,
... ]

// days
[ 2017-11-19 - 2017-11-20 : 37.9,
  2017-11-20 - 2017-11-21 : 31.1,
... ]

A DateInterval structure seems to be a perfect candidate for a key in this dictionary. But as I ran some basic tests I found that while date created with Date() init represents correct information on a given moment in time, the DateInterval structure from Calendar.current appears to be defaulting to GMT+0 as a timezone, so I'm getting following output:

let date = Date() //outputs "Nov 20, 2017 at 10:32 PM"
let hourInterval = Calendar.current.dateInterval(of: .hour, for: date)
//outputs: 2017-11-20 20:00:00 +0000 to 2017-11-20 21:00:00 +0000

So it's 2 hours off my/user's timezone. What is the correct way to use DateInterval so it doesn't shift in timezones?

Denys Triasunov
  • 539
  • 1
  • 4
  • 24

1 Answers1

1

The internal structure of dates in iOS is always GMT. What you're seeing is the string representation. The internal dates are still consistent with one another. Consider this playground code:

//: Playground - noun: a place where people can play

import UIKit
import XCTest
import PlaygroundSupport


let fourHours:Double = -1 * 60 * 60 * 4
var newDate = Date()
let oldDate = Date(timeInterval: fourHours, since: newDate)
let interval = DateInterval(start: oldDate, end: newDate)

let hourInterval = Calendar.current.dateInterval(of: .hour, for: newDate)

The output looks like this:

result

Even though the dates are show as local time (EST) the printable representation is in GMT. The times are offset though, so 'Nov 20, 2017 at 4:14 PM EST' is equivalent to '2017-11-20 21:14:09 +0000'. You can always retrieve the original date objects from the DateInterval with

hourInterval?.start
hourInterval?.end
David S.
  • 6,567
  • 1
  • 25
  • 45
  • Thanks for clearing the concept)) Just got confused because string representations will be used to display information in charts and I was afraid all components would get messed up. – Denys Triasunov Nov 20 '17 at 22:07