Erik
Erik

Reputation: 2530

Time difference with NSDateComponents

I'm building an app whereas I need to calculate the time between two NSDates.

I've subclassed NSObject and named it "MyObject" (simplified for the sake of this question).

It holds these two properties

@property (nonatomic, strong) NSDate *startDate;
@property (nonatomic, strong) NSDate *endDate;

I have an array storing x number of MyObjects, which I loop through like so

NSTimeInterval totalInterval = 0;
for (MyObject *currentObject in _listOfItems)
{
    totalInterval += [currentObject.endDate timeIntervalSinceDate:currentObject.startDate];
}

I'm using totalInterval to summarise the length of all the "spans" combined. I'm doing this by setting up 2 NSDates, simply for the sake of calculating the difference.

NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:totalInterval sinceDate:date1];

I'm setting up these flags:

unsigned int unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitDay | NSCalendarUnitMonth;

And return the result as NSDateComponent like so:

return [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];

My question: When I used the units above, I had the wrong result - namely 11h 20m when the real answer is about 83h. I learned that I was needlessly specifying the NSCalendarUnitDay and NSCalendarUnitMonth units. After reading the docs, I read that "There is no need to specify any more components than those in which you are interested" and I removed the two needlessly specified units. This gave me the right result, but how come? Why would it report the wrong result by simply specifying more units?

Thank you!

Upvotes: 2

Views: 122

Answers (2)

jscs
jscs

Reputation: 64002

The calculation will always begin with the largest units that you've asked for. So if you ask for days and hours, but then only inspect hours, you will see the actual total number of hours modulo 24. This applies to any date decomposition that NSCalendar performs.

Upvotes: 3

Joride
Joride

Reputation: 3763

Why would it report the wrong result by simply specifying more units?

The NSDateComponents represents all of the time between the two dates (300.000 seconds in your case), specified in a number of days (3), hours (11) and minutes (11).

Asking for just seconds will get you seconds, asking for seconds and days will give you just those. Asking just for days would give you the full number of days, so it would be 3. Note that NSDateComponents can either represent a date (point time), or a time interval.

This flexibility gives you the ability to create some pretty cool time-based components.

Upvotes: 0

Related Questions