简体   繁体   中英

Find out if two calendar days have past between two dates

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM