Curnelious
Curnelious

Reputation: 1

Days between date strange result

It might be stupid but i couldn't find why it happens, i am trying to calculate the difference between 2 dates with :

- (long)daysBetween:(NSDate *)dt1 and:(NSDate *)dt2
{
    NSUInteger unitFlags = NSCalendarUnitDay;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [calendar components:unitFlags fromDate:dt1 toDate:dt2 options:0];
    return [components day]+1;
}

call it with :

NSLog(@"%@ %@,%ld",currentdate,starteddate,[self daysBetween:starteddate and:currentdate]);
return [self daysBetween:starteddate and:currentdate];

on the log, for the same dates, sometimes it returns 7 sometimes 8 , why ??

logs for 2 different calls :

  2015-07-07 09:54:33 +0000 2015-06-30 09:54:33 +0000,7
  2015-07-07 09:54:33 +0000 2015-06-30 09:54:33 +0000,8

for the exact same 4 dates, i get different results as you see- 7 and 8 ...

Upvotes: 0

Views: 22

Answers (1)

user3693546
user3693546

Reputation:

I have had same problem once. Solved at setting the time zone -

Set the timezone before passing dates into this function

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

Upvotes: 2

Related Questions