-2

I tried something like this:

var calendar = Calendar.current
var dayFutureComponents = DateComponents()
dayFutureComponents.day = 1 // aka 1 day
var d = calendar.date(byAdding: dayFutureComponents, to: Date())
...//setting of d.hour, d.minute, d.second to zero and finding the difference between 2 dates

The problem is for example my current GMT is +3. So the result differs from one I need to achieve by 3 hours. How to fix this issue?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49

2 Answers2

1

First create a Calendar for the UTC timezone. Second get the startOfDay using the UTC calendar. Third add one day to that date. Then you can useDatemethodtimeIntervalSince(_ Date)` to calculate the amount of seconds between those two dates:

extension Calendar {
    static let iso8601UTC: Calendar = {
        var calendar = Calendar(identifier: .iso8601)
        calendar.timeZone = TimeZone(identifier: "UTC")!
        return calendar
    }()
}

extension Date {
    var secondsUntilStartOfDayTomorrowAtUTC: TimeInterval {
        return startOfDayTomorrowAtUTC.timeIntervalSince(self)
    }
    var startOfDayTomorrowAtUTC: Date {
        return Calendar.current.date(byAdding: .day, value: 1, to: startOfDayAtUTC)!
    }
    var startOfDayAtUTC: Date {
        return Calendar.iso8601UTC.startOfDay(for: self)
    }
}

Playground Testing:

TimeZone.current.secondsFromGMT(for: Date()) / 3600 // -2 hours
Date().startOfDayAtUTC          // "Jan 18, 2018 at 10:00 PM"
let finalDate = Date().startOfDayTomorrowAtUTC  // "Jan 19, 2018 at 10:00 PM"
print(finalDate)  // "2018-01-20 00:00:00 +0000\n"
let seconds = Date().secondsUntilStartOfDayTomorrowAtUTC  // 29282.42592203617
let minutes = seconds / 60   // 488.0404320339362
let hours = seconds / 3600   // 8.134007200565604
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • This will give startOfDay of tomorrow at local time. You still need to use the Calendar at UTC timezone – Leo Dabus Feb 25 '18 at 19:21
  • kkkk ninja edit. You forgot to change `Date()` to `self` – Leo Dabus Feb 25 '18 at 19:22
  • Your original comment was using `Calendar.current`. The solution is to set the Calendar timezone to UTC. Both approaches would work. I prefer to separate them to have more flexibility (I can get today or tomorrow) – Leo Dabus Feb 25 '18 at 19:24
  • I don't want to nitpick. I deleted my other comments. – vadian Feb 25 '18 at 19:32
  • @vadian no problem. Note that it is a bit more complex than it looks like if you consider that depending on the timezone and the current time you can be 1 day ahead or behind – Leo Dabus Feb 25 '18 at 19:34
0

Missed out that when I for example set hour to 0 - it displayed according to GMT (in my case it is 3 hours of difference). And When I calculate the difference between 2 dates - both dates has the same "displacement" so final result should be the same

Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49