Phil
Phil

Reputation: 3045

timeIntervalSinceDate in past?

I'm creating a NSDate in the past (1 hour in the past) and that looks to be setting correct, only thing is I want to then use that to determine if an even has happened or not. Because I set to be in the past, when I do the check it should definitely think the even has happened, but timeIntervalSinceDate seems to only give a positive result?

This is the code I'm using with timeIntervalSinceDate

 NSDate *now = [NSDate date];
  NSTimeInterval secondsSincePlantingInterval = [now timeIntervalSinceDate:plantingDate];

Which is giving 68 seconds, but it should be -68 seconds, or does it not return negative values?

Upvotes: 2

Views: 4156

Answers (2)

mattjgalloway
mattjgalloway

Reputation: 34912

It does return negative values, yes. But if plantingDate is in the past then I'd expect secondsSincePlantingInterval to be positive.

If you think about it, that line is reading:

Tell me the number of seconds now is since plantingDate.

Just like Tuesday 2nd is one day since Monday 1st, now is +ve seconds since plantingDate.

You want:

NSTimeInterval secondsSincePlantingInterval = [plantingDate timeIntervalSinceNow];

Upvotes: 3

Olotiar
Olotiar

Reputation: 3274

This is perfectly normal, documented behavior

The documentation states :

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

Return Value

The interval between the receiver and anotherDate. If the receiver is earlier than anotherDate, the return value is negative.

Since plantingDate is in the past, the receiver is not earlier than it. Therefore the value is positive.

Moreover ; this is plain english

 [now timeIntervalSinceDate:plantingDate];

So, the time interval since the plantingDate up to now is positive.

Upvotes: 5

Related Questions