0

I am trying to calculate the number of days from one date to another and have found two ways of doing so.

The first uses NSDateComponents as follows:

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                    fromDate:date1
                                                      toDate:date2
                                                     options:0];

and then checking the [components day].

The second uses timeInterval:

    NSInteger timeInterval = [date2 timeIntervalSinceDate:date1];

and then getting timeInterval/3600/24

Is one way better than the other (perhaps because of lack precision with the timeInterval methods)?

Thanks!

1 Answers1

1

Using dateComponent is far more better then manipulation yourself by assuming timeInterval/3600/24.

Reason:

  1. All days doesn't have 60*60*24 seconds!!!

  2. While transition from daylight saving time where one day can have 23 or 25 hours.

The hour (common symbol: h or hr) is a unit of measurement of time. In modern usage, an hour comprises 60 minutes, or 3,600 seconds. It is approximately 1/24 of a mean solar day.

An hour in the Universal Coordinated Time (UTC) time standard can include a negative or positive leap second, and may therefore have a duration of 3,599 or 3,601 seconds for adjustment purposes.

Source:Wikipedia Hour.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
  • 2
    Leap seconds are *not* the reason that you should use NSDateComponents, because the Unix time does not count leap seconds. The Unix time number increases exactly by 3600 every hour. - The real reason is the transition from and to Daylight Saving Time, where one day may have 23 or 25 hours. – Martin R May 09 '14 at 05:56
  • Thanks to both of you! Right on regarding DST. – sternhenri May 10 '14 at 03:43