0

When I compare the beginning to the end of the day of october 25, I get 89999 seconds (25 hours).

I compare the dates using the following method:

endOfDay.timeIntervalSinceDate(startOfDay)

However, when I compare the hours, I get 24. I use the following extension function of NSDate to compare hours.:

 func differenceInHoursWith(date: NSDate) -> Int{
        let components = NSCalendar.currentCalendar().components(.Hour, fromDate: self, toDate: date, options: [])
        return components.hour
    }

Is there a way to get the difference in seconds without day time adjustments ? In my case I do not need them and I need seconds granularity.

the Reverend
  • 12,305
  • 10
  • 66
  • 121
  • Since the USA sets its clocks back by an hour on that date, 25 hours is correct. If the result were 24 hours, it would be short by one hour. It actually is that many seconds. – Tom Harrington Oct 16 '15 at 21:35
  • Yes it is correct, but for my application I want to ignore day light calculations. – the Reverend Oct 16 '15 at 23:42
  • It's not "calculations" or an "adjustment", those two times are actually 25 hours apart. As in, if you started counting seconds at the start time, any accurate clock would take 25 hours to reach the end time. The framework isn't doing some arcane calculation, it's giving you a literally accurate result. – Tom Harrington Oct 16 '15 at 23:45
  • Tom I'm not arguing that its wrong. My point is, if you look at any calendar on the 25th, its still from hour 0 to 24. To display them I need the start and end dates of all events translated into graphical points transposed to the day's timeline. I know I can create a new NSCalendar instance with the GMT zone that will give me what I want. I just wanted to know if there was another way. I'm currently just adding up the seconds via the hour + minutes + seconds. I think that would be the easiest solution for me. – the Reverend Oct 17 '15 at 17:53

1 Answers1

0

There are 3600 seconds in an hour, so you can take the number of seconds and divide it by 3600. Here's an implementation that does that:

func differenceInHoursWith(date: NSDate) -> Int {
    let seconds = self.timeIntervalSinceDate(date)
    return Int(seconds / 3600)
}

If you want the absolute value of the difference you can do this:

func differenceInHoursWith(date: NSDate) -> Int {
    let seconds = self.timeIntervalSinceDate(date)
    let hours = Int(seconds / 3600)
    return abs(hours)
}
Jonathan
  • 925
  • 6
  • 19