문제

I want to find out if two calendar days have past between two dates.

I tried using

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date toDate:now options:0];
NSInteger days = [components day];  

and check if days >= 2, but it seems that its count days only if full day has past.

For example if the two dates are:
Monday 01:00 am
Sunday 11:00 pm

the result will be 0,
I expected to get 1 because Sunday is different day than monday.

도움이 되었습니까?

해결책

You have to "normalize" both dates to the start of the respective day:

NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startOfToday, *startOfOtherDay;
[cal rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];
[cal rangeOfUnit:NSDayCalendarUnit startDate:&startOfOtherDay interval:NULL forDate:date];

and then compute the difference:

NSDateComponents *components = [cal components:NSDayCalendarUnit fromDate:startOfOtherDay toDate:startOfToday options:0];
NSInteger days = [components day];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top