Aside from input and output of the functions, what is the difference between NSDate
's
func timeIntervalSinceDate(anotherDate: NSDate) -> NSTimeInterval
and NSCalendar
's
func components(unitFlags: NSCalendarUnit, fromDate startingDate: NSDate, toDate resultDate: NSDate, options opts: NSCalendarOptions) -> NSDateComponents
?
Which function is more precise? And which functions take into account daylight savings, leap seconds, etc.?
For example:
let today = NSDate()
let someDate = RandomFutureDate() // Assumes this gives random future date
let seconds = futureDate.timeIntervalSinceDate(today)
let anotherSeconds = NSCalendar.currentCalendar().components(.CalendarUnitSecond, fromDate: today, toDate: futureDate, options: nil).second
Which is more accurate/correct, seconds
or anotherSeconds
?
Note: seconds
may seem more accurate since it is a double, but does it take into account DST, leap seconds, etc.?
Its not that one is more accurate/precise. They do different things.
The timeIntervalSinceDate method gives you a raw calculation of the number of seconds difference between 2 dates, without any attempt to divide that difference into conventional units like minutes and seconds. I guess timeIntervalSinceDate is more precise because it gives you an answer in fractional seconds, with sub-millisecond precision.
Your second version uses a calendar object to calculate a whole number number of seconds between the 2 dates. That version can be used to figure out the number of years, months, weeks, days, etc. between 2 dates, and is very useful for "calendrical calculations" Obviously in your example you're only asking for the number of whole seconds difference.
As Martin R points out in his comment below, you can adjust your calendar code slightly and get very precise fractional seconds from an NSCalendar using CalendarUnitNanosecond.
NSDates are really just a thin wrapper around a count of the number of seconds since the OS X/iOS "epoch date". The timeIntervalSinceDate method is going to be lightning-fast, since it's just doing a simple floating point subtraction.
By comparison, code using NSCalendar and NSDateComponents can be quite complicated, and therefore slower to perform. Such calculations have to allow for different calendar systems, different numbers of days in each month, leap years, and lots of other edge cases.